Web Interface For Lite Argus Control modules
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

13926 lines
396 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /* @preserve
  2. * Leaflet 1.5.1+Detached: 2e3e0ffbe87f246eb76d86d2633ddd59b262830b.2e3e0ff, a JS library for interactive maps. http://leafletjs.com
  3. * (c) 2010-2018 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. var version = "1.5.1+HEAD.2e3e0ff";
  6. /*
  7. * @namespace Util
  8. *
  9. * Various utility functions, used by Leaflet internally.
  10. */
  11. var freeze = Object.freeze;
  12. Object.freeze = function (obj) { return obj; };
  13. // @function extend(dest: Object, src?: Object): Object
  14. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  15. function extend(dest) {
  16. var i, j, len, src;
  17. for (j = 1, len = arguments.length; j < len; j++) {
  18. src = arguments[j];
  19. for (i in src) {
  20. dest[i] = src[i];
  21. }
  22. }
  23. return dest;
  24. }
  25. // @function create(proto: Object, properties?: Object): Object
  26. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  27. var create = Object.create || (function () {
  28. function F() {}
  29. return function (proto) {
  30. F.prototype = proto;
  31. return new F();
  32. };
  33. })();
  34. // @function bind(fn: Function, …): Function
  35. // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  36. // Has a `L.bind()` shortcut.
  37. function bind(fn, obj) {
  38. var slice = Array.prototype.slice;
  39. if (fn.bind) {
  40. return fn.bind.apply(fn, slice.call(arguments, 1));
  41. }
  42. var args = slice.call(arguments, 2);
  43. return function () {
  44. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  45. };
  46. }
  47. // @property lastId: Number
  48. // Last unique ID used by [`stamp()`](#util-stamp)
  49. var lastId = 0;
  50. // @function stamp(obj: Object): Number
  51. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  52. function stamp(obj) {
  53. /*eslint-disable */
  54. obj._leaflet_id = obj._leaflet_id || ++lastId;
  55. return obj._leaflet_id;
  56. /* eslint-enable */
  57. }
  58. // @function throttle(fn: Function, time: Number, context: Object): Function
  59. // Returns a function which executes function `fn` with the given scope `context`
  60. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  61. // `fn` will be called no more than one time per given amount of `time`. The arguments
  62. // received by the bound function will be any arguments passed when binding the
  63. // function, followed by any arguments passed when invoking the bound function.
  64. // Has an `L.throttle` shortcut.
  65. function throttle(fn, time, context) {
  66. var lock, args, wrapperFn, later;
  67. later = function () {
  68. // reset lock and call if queued
  69. lock = false;
  70. if (args) {
  71. wrapperFn.apply(context, args);
  72. args = false;
  73. }
  74. };
  75. wrapperFn = function () {
  76. if (lock) {
  77. // called too soon, queue to call later
  78. args = arguments;
  79. } else {
  80. // call and lock until later
  81. fn.apply(context, arguments);
  82. setTimeout(later, time);
  83. lock = true;
  84. }
  85. };
  86. return wrapperFn;
  87. }
  88. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  89. // Returns the number `num` modulo `range` in such a way so it lies within
  90. // `range[0]` and `range[1]`. The returned value will be always smaller than
  91. // `range[1]` unless `includeMax` is set to `true`.
  92. function wrapNum(x, range, includeMax) {
  93. var max = range[1],
  94. min = range[0],
  95. d = max - min;
  96. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  97. }
  98. // @function falseFn(): Function
  99. // Returns a function which always returns `false`.
  100. function falseFn() { return false; }
  101. // @function formatNum(num: Number, digits?: Number): Number
  102. // Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default.
  103. function formatNum(num, digits) {
  104. digits = (digits === undefined ? 6 : digits);
  105. return +(Math.round(num + ('e+' + digits)) + ('e-' + digits));
  106. }
  107. // @function trim(str: String): String
  108. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  109. function trim(str) {
  110. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  111. }
  112. // @function splitWords(str: String): String[]
  113. // Trims and splits the string on whitespace and returns the array of parts.
  114. function splitWords(str) {
  115. return trim(str).split(/\s+/);
  116. }
  117. // @function setOptions(obj: Object, options: Object): Object
  118. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  119. function setOptions(obj, options) {
  120. if (!obj.hasOwnProperty('options')) {
  121. obj.options = obj.options ? create(obj.options) : {};
  122. }
  123. for (var i in options) {
  124. obj.options[i] = options[i];
  125. }
  126. return obj.options;
  127. }
  128. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  129. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  130. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  131. // be appended at the end. If `uppercase` is `true`, the parameter names will
  132. // be uppercased (e.g. `'?A=foo&B=bar'`)
  133. function getParamString(obj, existingUrl, uppercase) {
  134. var params = [];
  135. for (var i in obj) {
  136. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  137. }
  138. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  139. }
  140. var templateRe = /\{ *([\w_-]+) *\}/g;
  141. // @function template(str: String, data: Object): String
  142. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  143. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  144. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  145. // data values — they will be evaluated passing `data` as an argument.
  146. function template(str, data) {
  147. return str.replace(templateRe, function (str, key) {
  148. var value = data[key];
  149. if (value === undefined) {
  150. throw new Error('No value provided for variable ' + str);
  151. } else if (typeof value === 'function') {
  152. value = value(data);
  153. }
  154. return value;
  155. });
  156. }
  157. // @function isArray(obj): Boolean
  158. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  159. var isArray = Array.isArray || function (obj) {
  160. return (Object.prototype.toString.call(obj) === '[object Array]');
  161. };
  162. // @function indexOf(array: Array, el: Object): Number
  163. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  164. function indexOf(array, el) {
  165. for (var i = 0; i < array.length; i++) {
  166. if (array[i] === el) { return i; }
  167. }
  168. return -1;
  169. }
  170. // @property emptyImageUrl: String
  171. // Data URI string containing a base64-encoded empty GIF image.
  172. // Used as a hack to free memory from unused images on WebKit-powered
  173. // mobile devices (by setting image `src` to this string).
  174. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  175. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  176. function getPrefixed(name) {
  177. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  178. }
  179. var lastTime = 0;
  180. // fallback for IE 7-8
  181. function timeoutDefer(fn) {
  182. var time = +new Date(),
  183. timeToCall = Math.max(0, 16 - (time - lastTime));
  184. lastTime = time + timeToCall;
  185. return window.setTimeout(fn, timeToCall);
  186. }
  187. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  188. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  189. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  190. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  191. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  192. // `context` if given. When `immediate` is set, `fn` is called immediately if
  193. // the browser doesn't have native support for
  194. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  195. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  196. function requestAnimFrame(fn, context, immediate) {
  197. if (immediate && requestFn === timeoutDefer) {
  198. fn.call(context);
  199. } else {
  200. return requestFn.call(window, bind(fn, context));
  201. }
  202. }
  203. // @function cancelAnimFrame(id: Number): undefined
  204. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  205. function cancelAnimFrame(id) {
  206. if (id) {
  207. cancelFn.call(window, id);
  208. }
  209. }
  210. var Util = (Object.freeze || Object)({
  211. freeze: freeze,
  212. extend: extend,
  213. create: create,
  214. bind: bind,
  215. lastId: lastId,
  216. stamp: stamp,
  217. throttle: throttle,
  218. wrapNum: wrapNum,
  219. falseFn: falseFn,
  220. formatNum: formatNum,
  221. trim: trim,
  222. splitWords: splitWords,
  223. setOptions: setOptions,
  224. getParamString: getParamString,
  225. template: template,
  226. isArray: isArray,
  227. indexOf: indexOf,
  228. emptyImageUrl: emptyImageUrl,
  229. requestFn: requestFn,
  230. cancelFn: cancelFn,
  231. requestAnimFrame: requestAnimFrame,
  232. cancelAnimFrame: cancelAnimFrame
  233. });
  234. // @class Class
  235. // @aka L.Class
  236. // @section
  237. // @uninheritable
  238. // Thanks to John Resig and Dean Edwards for inspiration!
  239. function Class() {}
  240. Class.extend = function (props) {
  241. // @function extend(props: Object): Function
  242. // [Extends the current class](#class-inheritance) given the properties to be included.
  243. // Returns a Javascript function that is a class constructor (to be called with `new`).
  244. var NewClass = function () {
  245. // call the constructor
  246. if (this.initialize) {
  247. this.initialize.apply(this, arguments);
  248. }
  249. // call all constructor hooks
  250. this.callInitHooks();
  251. };
  252. var parentProto = NewClass.__super__ = this.prototype;
  253. var proto = create(parentProto);
  254. proto.constructor = NewClass;
  255. NewClass.prototype = proto;
  256. // inherit parent's statics
  257. for (var i in this) {
  258. if (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {
  259. NewClass[i] = this[i];
  260. }
  261. }
  262. // mix static properties into the class
  263. if (props.statics) {
  264. extend(NewClass, props.statics);
  265. delete props.statics;
  266. }
  267. // mix includes into the prototype
  268. if (props.includes) {
  269. checkDeprecatedMixinEvents(props.includes);
  270. extend.apply(null, [proto].concat(props.includes));
  271. delete props.includes;
  272. }
  273. // merge options
  274. if (proto.options) {
  275. props.options = extend(create(proto.options), props.options);
  276. }
  277. // mix given properties into the prototype
  278. extend(proto, props);
  279. proto._initHooks = [];
  280. // add method for calling all hooks
  281. proto.callInitHooks = function () {
  282. if (this._initHooksCalled) { return; }
  283. if (parentProto.callInitHooks) {
  284. parentProto.callInitHooks.call(this);
  285. }
  286. this._initHooksCalled = true;
  287. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  288. proto._initHooks[i].call(this);
  289. }
  290. };
  291. return NewClass;
  292. };
  293. // @function include(properties: Object): this
  294. // [Includes a mixin](#class-includes) into the current class.
  295. Class.include = function (props) {
  296. extend(this.prototype, props);
  297. return this;
  298. };
  299. // @function mergeOptions(options: Object): this
  300. // [Merges `options`](#class-options) into the defaults of the class.
  301. Class.mergeOptions = function (options) {
  302. extend(this.prototype.options, options);
  303. return this;
  304. };
  305. // @function addInitHook(fn: Function): this
  306. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  307. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  308. var args = Array.prototype.slice.call(arguments, 1);
  309. var init = typeof fn === 'function' ? fn : function () {
  310. this[fn].apply(this, args);
  311. };
  312. this.prototype._initHooks = this.prototype._initHooks || [];
  313. this.prototype._initHooks.push(init);
  314. return this;
  315. };
  316. function checkDeprecatedMixinEvents(includes) {
  317. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  318. includes = isArray(includes) ? includes : [includes];
  319. for (var i = 0; i < includes.length; i++) {
  320. if (includes[i] === L.Mixin.Events) {
  321. console.warn('Deprecated include of L.Mixin.Events: ' +
  322. 'this property will be removed in future releases, ' +
  323. 'please inherit from L.Evented instead.', new Error().stack);
  324. }
  325. }
  326. }
  327. /*
  328. * @class Evented
  329. * @aka L.Evented
  330. * @inherits Class
  331. *
  332. * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).
  333. *
  334. * @example
  335. *
  336. * ```js
  337. * map.on('click', function(e) {
  338. * alert(e.latlng);
  339. * } );
  340. * ```
  341. *
  342. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  343. *
  344. * ```js
  345. * function onClick(e) { ... }
  346. *
  347. * map.on('click', onClick);
  348. * map.off('click', onClick);
  349. * ```
  350. */
  351. var Events = {
  352. /* @method on(type: String, fn: Function, context?: Object): this
  353. * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).
  354. *
  355. * @alternative
  356. * @method on(eventMap: Object): this
  357. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  358. */
  359. on: function (types, fn, context) {
  360. // types can be a map of types/handlers
  361. if (typeof types === 'object') {
  362. for (var type in types) {
  363. // we don't process space-separated events here for performance;
  364. // it's a hot path since Layer uses the on(obj) syntax
  365. this._on(type, types[type], fn);
  366. }
  367. } else {
  368. // types can be a string of space-separated words
  369. types = splitWords(types);
  370. for (var i = 0, len = types.length; i < len; i++) {
  371. this._on(types[i], fn, context);
  372. }
  373. }
  374. return this;
  375. },
  376. /* @method off(type: String, fn?: Function, context?: Object): this
  377. * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.
  378. *
  379. * @alternative
  380. * @method off(eventMap: Object): this
  381. * Removes a set of type/listener pairs.
  382. *
  383. * @alternative
  384. * @method off: this
  385. * Removes all listeners to all events on the object. This includes implicitly attached events.
  386. */
  387. off: function (types, fn, context) {
  388. if (!types) {
  389. // clear all listeners if called without arguments
  390. delete this._events;
  391. } else if (typeof types === 'object') {
  392. for (var type in types) {
  393. this._off(type, types[type], fn);
  394. }
  395. } else {
  396. types = splitWords(types);
  397. for (var i = 0, len = types.length; i < len; i++) {
  398. this._off(types[i], fn, context);
  399. }
  400. }
  401. return this;
  402. },
  403. // attach listener (without syntactic sugar now)
  404. _on: function (type, fn, context) {
  405. this._events = this._events || {};
  406. /* get/init listeners for type */
  407. var typeListeners = this._events[type];
  408. if (!typeListeners) {
  409. typeListeners = [];
  410. this._events[type] = typeListeners;
  411. }
  412. if (context === this) {
  413. // Less memory footprint.
  414. context = undefined;
  415. }
  416. var newListener = {fn: fn, ctx: context},
  417. listeners = typeListeners;
  418. // check if fn already there
  419. for (var i = 0, len = listeners.length; i < len; i++) {
  420. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  421. return;
  422. }
  423. }
  424. listeners.push(newListener);
  425. },
  426. _off: function (type, fn, context) {
  427. var listeners,
  428. i,
  429. len;
  430. if (!this._events) { return; }
  431. listeners = this._events[type];
  432. if (!listeners) {
  433. return;
  434. }
  435. if (!fn) {
  436. // Set all removed listeners to noop so they are not called if remove happens in fire
  437. for (i = 0, len = listeners.length; i < len; i++) {
  438. listeners[i].fn = falseFn;
  439. }
  440. // clear all listeners for a type if function isn't specified
  441. delete this._events[type];
  442. return;
  443. }
  444. if (context === this) {
  445. context = undefined;
  446. }
  447. if (listeners) {
  448. // find fn and remove it
  449. for (i = 0, len = listeners.length; i < len; i++) {
  450. var l = listeners[i];
  451. if (l.ctx !== context) { continue; }
  452. if (l.fn === fn) {
  453. // set the removed listener to noop so that's not called if remove happens in fire
  454. l.fn = falseFn;
  455. if (this._firingCount) {
  456. /* copy array in case events are being fired */
  457. this._events[type] = listeners = listeners.slice();
  458. }
  459. listeners.splice(i, 1);
  460. return;
  461. }
  462. }
  463. }
  464. },
  465. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  466. // Fires an event of the specified type. You can optionally provide an data
  467. // object — the first argument of the listener function will contain its
  468. // properties. The event can optionally be propagated to event parents.
  469. fire: function (type, data, propagate) {
  470. if (!this.listens(type, propagate)) { return this; }
  471. var event = extend({}, data, {
  472. type: type,
  473. target: this,
  474. sourceTarget: data && data.sourceTarget || this
  475. });
  476. if (this._events) {
  477. var listeners = this._events[type];
  478. if (listeners) {
  479. this._firingCount = (this._firingCount + 1) || 1;
  480. for (var i = 0, len = listeners.length; i < len; i++) {
  481. var l = listeners[i];
  482. l.fn.call(l.ctx || this, event);
  483. }
  484. this._firingCount--;
  485. }
  486. }
  487. if (propagate) {
  488. // propagate the event to parents (set with addEventParent)
  489. this._propagateEvent(event);
  490. }
  491. return this;
  492. },
  493. // @method listens(type: String): Boolean
  494. // Returns `true` if a particular event type has any listeners attached to it.
  495. listens: function (type, propagate) {
  496. var listeners = this._events && this._events[type];
  497. if (listeners && listeners.length) { return true; }
  498. if (propagate) {
  499. // also check parents for listeners if event propagates
  500. for (var id in this._eventParents) {
  501. if (this._eventParents[id].listens(type, propagate)) { return true; }
  502. }
  503. }
  504. return false;
  505. },
  506. // @method once(…): this
  507. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  508. once: function (types, fn, context) {
  509. if (typeof types === 'object') {
  510. for (var type in types) {
  511. this.once(type, types[type], fn);
  512. }
  513. return this;
  514. }
  515. var handler = bind(function () {
  516. this
  517. .off(types, fn, context)
  518. .off(types, handler, context);
  519. }, this);
  520. // add a listener that's executed once and removed after that
  521. return this
  522. .on(types, fn, context)
  523. .on(types, handler, context);
  524. },
  525. // @method addEventParent(obj: Evented): this
  526. // Adds an event parent - an `Evented` that will receive propagated events
  527. addEventParent: function (obj) {
  528. this._eventParents = this._eventParents || {};
  529. this._eventParents[stamp(obj)] = obj;
  530. return this;
  531. },
  532. // @method removeEventParent(obj: Evented): this
  533. // Removes an event parent, so it will stop receiving propagated events
  534. removeEventParent: function (obj) {
  535. if (this._eventParents) {
  536. delete this._eventParents[stamp(obj)];
  537. }
  538. return this;
  539. },
  540. _propagateEvent: function (e) {
  541. for (var id in this._eventParents) {
  542. this._eventParents[id].fire(e.type, extend({
  543. layer: e.target,
  544. propagatedFrom: e.target
  545. }, e), true);
  546. }
  547. }
  548. };
  549. // aliases; we should ditch those eventually
  550. // @method addEventListener(…): this
  551. // Alias to [`on(…)`](#evented-on)
  552. Events.addEventListener = Events.on;
  553. // @method removeEventListener(…): this
  554. // Alias to [`off(…)`](#evented-off)
  555. // @method clearAllEventListeners(…): this
  556. // Alias to [`off()`](#evented-off)
  557. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  558. // @method addOneTimeEventListener(…): this
  559. // Alias to [`once(…)`](#evented-once)
  560. Events.addOneTimeEventListener = Events.once;
  561. // @method fireEvent(…): this
  562. // Alias to [`fire(…)`](#evented-fire)
  563. Events.fireEvent = Events.fire;
  564. // @method hasEventListeners(…): Boolean
  565. // Alias to [`listens(…)`](#evented-listens)
  566. Events.hasEventListeners = Events.listens;
  567. var Evented = Class.extend(Events);
  568. /*
  569. * @class Point
  570. * @aka L.Point
  571. *
  572. * Represents a point with `x` and `y` coordinates in pixels.
  573. *
  574. * @example
  575. *
  576. * ```js
  577. * var point = L.point(200, 300);
  578. * ```
  579. *
  580. * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:
  581. *
  582. * ```js
  583. * map.panBy([200, 300]);
  584. * map.panBy(L.point(200, 300));
  585. * ```
  586. *
  587. * Note that `Point` does not inherit from Leafet's `Class` object,
  588. * which means new classes can't inherit from it, and new methods
  589. * can't be added to it with the `include` function.
  590. */
  591. function Point(x, y, round) {
  592. // @property x: Number; The `x` coordinate of the point
  593. this.x = (round ? Math.round(x) : x);
  594. // @property y: Number; The `y` coordinate of the point
  595. this.y = (round ? Math.round(y) : y);
  596. }
  597. var trunc = Math.trunc || function (v) {
  598. return v > 0 ? Math.floor(v) : Math.ceil(v);
  599. };
  600. Point.prototype = {
  601. // @method clone(): Point
  602. // Returns a copy of the current point.
  603. clone: function () {
  604. return new Point(this.x, this.y);
  605. },
  606. // @method add(otherPoint: Point): Point
  607. // Returns the result of addition of the current and the given points.
  608. add: function (point) {
  609. // non-destructive, returns a new point
  610. return this.clone()._add(toPoint(point));
  611. },
  612. _add: function (point) {
  613. // destructive, used directly for performance in situations where it's safe to modify existing point
  614. this.x += point.x;
  615. this.y += point.y;
  616. return this;
  617. },
  618. // @method subtract(otherPoint: Point): Point
  619. // Returns the result of subtraction of the given point from the current.
  620. subtract: function (point) {
  621. return this.clone()._subtract(toPoint(point));
  622. },
  623. _subtract: function (point) {
  624. this.x -= point.x;
  625. this.y -= point.y;
  626. return this;
  627. },
  628. // @method divideBy(num: Number): Point
  629. // Returns the result of division of the current point by the given number.
  630. divideBy: function (num) {
  631. return this.clone()._divideBy(num);
  632. },
  633. _divideBy: function (num) {
  634. this.x /= num;
  635. this.y /= num;
  636. return this;
  637. },
  638. // @method multiplyBy(num: Number): Point
  639. // Returns the result of multiplication of the current point by the given number.
  640. multiplyBy: function (num) {
  641. return this.clone()._multiplyBy(num);
  642. },
  643. _multiplyBy: function (num) {
  644. this.x *= num;
  645. this.y *= num;
  646. return this;
  647. },
  648. // @method scaleBy(scale: Point): Point
  649. // Multiply each coordinate of the current point by each coordinate of
  650. // `scale`. In linear algebra terms, multiply the point by the
  651. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  652. // defined by `scale`.
  653. scaleBy: function (point) {
  654. return new Point(this.x * point.x, this.y * point.y);
  655. },
  656. // @method unscaleBy(scale: Point): Point
  657. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  658. // each coordinate of `scale`.
  659. unscaleBy: function (point) {
  660. return new Point(this.x / point.x, this.y / point.y);
  661. },
  662. // @method round(): Point
  663. // Returns a copy of the current point with rounded coordinates.
  664. round: function () {
  665. return this.clone()._round();
  666. },
  667. _round: function () {
  668. this.x = Math.round(this.x);
  669. this.y = Math.round(this.y);
  670. return this;
  671. },
  672. // @method floor(): Point
  673. // Returns a copy of the current point with floored coordinates (rounded down).
  674. floor: function () {
  675. return this.clone()._floor();
  676. },
  677. _floor: function () {
  678. this.x = Math.floor(this.x);
  679. this.y = Math.floor(this.y);
  680. return this;
  681. },
  682. // @method ceil(): Point
  683. // Returns a copy of the current point with ceiled coordinates (rounded up).
  684. ceil: function () {
  685. return this.clone()._ceil();
  686. },
  687. _ceil: function () {
  688. this.x = Math.ceil(this.x);
  689. this.y = Math.ceil(this.y);
  690. return this;
  691. },
  692. // @method trunc(): Point
  693. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  694. trunc: function () {
  695. return this.clone()._trunc();
  696. },
  697. _trunc: function () {
  698. this.x = trunc(this.x);
  699. this.y = trunc(this.y);
  700. return this;
  701. },
  702. // @method distanceTo(otherPoint: Point): Number
  703. // Returns the cartesian distance between the current and the given points.
  704. distanceTo: function (point) {
  705. point = toPoint(point);
  706. var x = point.x - this.x,
  707. y = point.y - this.y;
  708. return Math.sqrt(x * x + y * y);
  709. },
  710. // @method equals(otherPoint: Point): Boolean
  711. // Returns `true` if the given point has the same coordinates.
  712. equals: function (point) {
  713. point = toPoint(point);
  714. return point.x === this.x &&
  715. point.y === this.y;
  716. },
  717. // @method contains(otherPoint: Point): Boolean
  718. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  719. contains: function (point) {
  720. point = toPoint(point);
  721. return Math.abs(point.x) <= Math.abs(this.x) &&
  722. Math.abs(point.y) <= Math.abs(this.y);
  723. },
  724. // @method toString(): String
  725. // Returns a string representation of the point for debugging purposes.
  726. toString: function () {
  727. return 'Point(' +
  728. formatNum(this.x) + ', ' +
  729. formatNum(this.y) + ')';
  730. }
  731. };
  732. // @factory L.point(x: Number, y: Number, round?: Boolean)
  733. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  734. // @alternative
  735. // @factory L.point(coords: Number[])
  736. // Expects an array of the form `[x, y]` instead.
  737. // @alternative
  738. // @factory L.point(coords: Object)
  739. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  740. function toPoint(x, y, round) {
  741. if (x instanceof Point) {
  742. return x;
  743. }
  744. if (isArray(x)) {
  745. return new Point(x[0], x[1]);
  746. }
  747. if (x === undefined || x === null) {
  748. return x;
  749. }
  750. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  751. return new Point(x.x, x.y);
  752. }
  753. return new Point(x, y, round);
  754. }
  755. /*
  756. * @class Bounds
  757. * @aka L.Bounds
  758. *
  759. * Represents a rectangular area in pixel coordinates.
  760. *
  761. * @example
  762. *
  763. * ```js
  764. * var p1 = L.point(10, 10),
  765. * p2 = L.point(40, 60),
  766. * bounds = L.bounds(p1, p2);
  767. * ```
  768. *
  769. * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
  770. *
  771. * ```js
  772. * otherBounds.intersects([[10, 10], [40, 60]]);
  773. * ```
  774. *
  775. * Note that `Bounds` does not inherit from Leafet's `Class` object,
  776. * which means new classes can't inherit from it, and new methods
  777. * can't be added to it with the `include` function.
  778. */
  779. function Bounds(a, b) {
  780. if (!a) { return; }
  781. var points = b ? [a, b] : a;
  782. for (var i = 0, len = points.length; i < len; i++) {
  783. this.extend(points[i]);
  784. }
  785. }
  786. Bounds.prototype = {
  787. // @method extend(point: Point): this
  788. // Extends the bounds to contain the given point.
  789. extend: function (point) { // (Point)
  790. point = toPoint(point);
  791. // @property min: Point
  792. // The top left corner of the rectangle.
  793. // @property max: Point
  794. // The bottom right corner of the rectangle.
  795. if (!this.min && !this.max) {
  796. this.min = point.clone();
  797. this.max = point.clone();
  798. } else {
  799. this.min.x = Math.min(point.x, this.min.x);
  800. this.max.x = Math.max(point.x, this.max.x);
  801. this.min.y = Math.min(point.y, this.min.y);
  802. this.max.y = Math.max(point.y, this.max.y);
  803. }
  804. return this;
  805. },
  806. // @method getCenter(round?: Boolean): Point
  807. // Returns the center point of the bounds.
  808. getCenter: function (round) {
  809. return new Point(
  810. (this.min.x + this.max.x) / 2,
  811. (this.min.y + this.max.y) / 2, round);
  812. },
  813. // @method getBottomLeft(): Point
  814. // Returns the bottom-left point of the bounds.
  815. getBottomLeft: function () {
  816. return new Point(this.min.x, this.max.y);
  817. },
  818. // @method getTopRight(): Point
  819. // Returns the top-right point of the bounds.
  820. getTopRight: function () { // -> Point
  821. return new Point(this.max.x, this.min.y);
  822. },
  823. // @method getTopLeft(): Point
  824. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  825. getTopLeft: function () {
  826. return this.min; // left, top
  827. },
  828. // @method getBottomRight(): Point
  829. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  830. getBottomRight: function () {
  831. return this.max; // right, bottom
  832. },
  833. // @method getSize(): Point
  834. // Returns the size of the given bounds
  835. getSize: function () {
  836. return this.max.subtract(this.min);
  837. },
  838. // @method contains(otherBounds: Bounds): Boolean
  839. // Returns `true` if the rectangle contains the given one.
  840. // @alternative
  841. // @method contains(point: Point): Boolean
  842. // Returns `true` if the rectangle contains the given point.
  843. contains: function (obj) {
  844. var min, max;
  845. if (typeof obj[0] === 'number' || obj instanceof Point) {
  846. obj = toPoint(obj);
  847. } else {
  848. obj = toBounds(obj);
  849. }
  850. if (obj instanceof Bounds) {
  851. min = obj.min;
  852. max = obj.max;
  853. } else {
  854. min = max = obj;
  855. }
  856. return (min.x >= this.min.x) &&
  857. (max.x <= this.max.x) &&
  858. (min.y >= this.min.y) &&
  859. (max.y <= this.max.y);
  860. },
  861. // @method intersects(otherBounds: Bounds): Boolean
  862. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  863. // intersect if they have at least one point in common.
  864. intersects: function (bounds) { // (Bounds) -> Boolean
  865. bounds = toBounds(bounds);
  866. var min = this.min,
  867. max = this.max,
  868. min2 = bounds.min,
  869. max2 = bounds.max,
  870. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  871. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  872. return xIntersects && yIntersects;
  873. },
  874. // @method overlaps(otherBounds: Bounds): Boolean
  875. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  876. // overlap if their intersection is an area.
  877. overlaps: function (bounds) { // (Bounds) -> Boolean
  878. bounds = toBounds(bounds);
  879. var min = this.min,
  880. max = this.max,
  881. min2 = bounds.min,
  882. max2 = bounds.max,
  883. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  884. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  885. return xOverlaps && yOverlaps;
  886. },
  887. isValid: function () {
  888. return !!(this.min && this.max);
  889. }
  890. };
  891. // @factory L.bounds(corner1: Point, corner2: Point)
  892. // Creates a Bounds object from two corners coordinate pairs.
  893. // @alternative
  894. // @factory L.bounds(points: Point[])
  895. // Creates a Bounds object from the given array of points.
  896. function toBounds(a, b) {
  897. if (!a || a instanceof Bounds) {
  898. return a;
  899. }
  900. return new Bounds(a, b);
  901. }
  902. /*
  903. * @class LatLngBounds
  904. * @aka L.LatLngBounds
  905. *
  906. * Represents a rectangular geographical area on a map.
  907. *
  908. * @example
  909. *
  910. * ```js
  911. * var corner1 = L.latLng(40.712, -74.227),
  912. * corner2 = L.latLng(40.774, -74.125),
  913. * bounds = L.latLngBounds(corner1, corner2);
  914. * ```
  915. *
  916. * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
  917. *
  918. * ```js
  919. * map.fitBounds([
  920. * [40.712, -74.227],
  921. * [40.774, -74.125]
  922. * ]);
  923. * ```
  924. *
  925. * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.
  926. *
  927. * Note that `LatLngBounds` does not inherit from Leafet's `Class` object,
  928. * which means new classes can't inherit from it, and new methods
  929. * can't be added to it with the `include` function.
  930. */
  931. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  932. if (!corner1) { return; }
  933. var latlngs = corner2 ? [corner1, corner2] : corner1;
  934. for (var i = 0, len = latlngs.length; i < len; i++) {
  935. this.extend(latlngs[i]);
  936. }
  937. }
  938. LatLngBounds.prototype = {
  939. // @method extend(latlng: LatLng): this
  940. // Extend the bounds to contain the given point
  941. // @alternative
  942. // @method extend(otherBounds: LatLngBounds): this
  943. // Extend the bounds to contain the given bounds
  944. extend: function (obj) {
  945. var sw = this._southWest,
  946. ne = this._northEast,
  947. sw2, ne2;
  948. if (obj instanceof LatLng) {
  949. sw2 = obj;
  950. ne2 = obj;
  951. } else if (obj instanceof LatLngBounds) {
  952. sw2 = obj._southWest;
  953. ne2 = obj._northEast;
  954. if (!sw2 || !ne2) { return this; }
  955. } else {
  956. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  957. }
  958. if (!sw && !ne) {
  959. this._southWest = new LatLng(sw2.lat, sw2.lng);
  960. this._northEast = new LatLng(ne2.lat, ne2.lng);
  961. } else {
  962. sw.lat = Math.min(sw2.lat, sw.lat);
  963. sw.lng = Math.min(sw2.lng, sw.lng);
  964. ne.lat = Math.max(ne2.lat, ne.lat);
  965. ne.lng = Math.max(ne2.lng, ne.lng);
  966. }
  967. return this;
  968. },
  969. // @method pad(bufferRatio: Number): LatLngBounds
  970. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  971. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  972. // Negative values will retract the bounds.
  973. pad: function (bufferRatio) {
  974. var sw = this._southWest,
  975. ne = this._northEast,
  976. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  977. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  978. return new LatLngBounds(
  979. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  980. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  981. },
  982. // @method getCenter(): LatLng
  983. // Returns the center point of the bounds.
  984. getCenter: function () {
  985. return new LatLng(
  986. (this._southWest.lat + this._northEast.lat) / 2,
  987. (this._southWest.lng + this._northEast.lng) / 2);
  988. },
  989. // @method getSouthWest(): LatLng
  990. // Returns the south-west point of the bounds.
  991. getSouthWest: function () {
  992. return this._southWest;
  993. },
  994. // @method getNorthEast(): LatLng
  995. // Returns the north-east point of the bounds.
  996. getNorthEast: function () {
  997. return this._northEast;
  998. },
  999. // @method getNorthWest(): LatLng
  1000. // Returns the north-west point of the bounds.
  1001. getNorthWest: function () {
  1002. return new LatLng(this.getNorth(), this.getWest());
  1003. },
  1004. // @method getSouthEast(): LatLng
  1005. // Returns the south-east point of the bounds.
  1006. getSouthEast: function () {
  1007. return new LatLng(this.getSouth(), this.getEast());
  1008. },
  1009. // @method getWest(): Number
  1010. // Returns the west longitude of the bounds
  1011. getWest: function () {
  1012. return this._southWest.lng;
  1013. },
  1014. // @method getSouth(): Number
  1015. // Returns the south latitude of the bounds
  1016. getSouth: function () {
  1017. return this._southWest.lat;
  1018. },
  1019. // @method getEast(): Number
  1020. // Returns the east longitude of the bounds
  1021. getEast: function () {
  1022. return this._northEast.lng;
  1023. },
  1024. // @method getNorth(): Number
  1025. // Returns the north latitude of the bounds
  1026. getNorth: function () {
  1027. return this._northEast.lat;
  1028. },
  1029. // @method contains(otherBounds: LatLngBounds): Boolean
  1030. // Returns `true` if the rectangle contains the given one.
  1031. // @alternative
  1032. // @method contains (latlng: LatLng): Boolean
  1033. // Returns `true` if the rectangle contains the given point.
  1034. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1035. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1036. obj = toLatLng(obj);
  1037. } else {
  1038. obj = toLatLngBounds(obj);
  1039. }
  1040. var sw = this._southWest,
  1041. ne = this._northEast,
  1042. sw2, ne2;
  1043. if (obj instanceof LatLngBounds) {
  1044. sw2 = obj.getSouthWest();
  1045. ne2 = obj.getNorthEast();
  1046. } else {
  1047. sw2 = ne2 = obj;
  1048. }
  1049. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1050. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1051. },
  1052. // @method intersects(otherBounds: LatLngBounds): Boolean
  1053. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1054. intersects: function (bounds) {
  1055. bounds = toLatLngBounds(bounds);
  1056. var sw = this._southWest,
  1057. ne = this._northEast,
  1058. sw2 = bounds.getSouthWest(),
  1059. ne2 = bounds.getNorthEast(),
  1060. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1061. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1062. return latIntersects && lngIntersects;
  1063. },
  1064. // @method overlaps(otherBounds: Bounds): Boolean
  1065. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1066. overlaps: function (bounds) {
  1067. bounds = toLatLngBounds(bounds);
  1068. var sw = this._southWest,
  1069. ne = this._northEast,
  1070. sw2 = bounds.getSouthWest(),
  1071. ne2 = bounds.getNorthEast(),
  1072. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1073. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1074. return latOverlaps && lngOverlaps;
  1075. },
  1076. // @method toBBoxString(): String
  1077. // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.
  1078. toBBoxString: function () {
  1079. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1080. },
  1081. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1082. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
  1083. equals: function (bounds, maxMargin) {
  1084. if (!bounds) { return false; }
  1085. bounds = toLatLngBounds(bounds);
  1086. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1087. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1088. },
  1089. // @method isValid(): Boolean
  1090. // Returns `true` if the bounds are properly initialized.
  1091. isValid: function () {
  1092. return !!(this._southWest && this._northEast);
  1093. }
  1094. };
  1095. // TODO International date line?
  1096. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1097. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1098. // @alternative
  1099. // @factory L.latLngBounds(latlngs: LatLng[])
  1100. // Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).
  1101. function toLatLngBounds(a, b) {
  1102. if (a instanceof LatLngBounds) {
  1103. return a;
  1104. }
  1105. return new LatLngBounds(a, b);
  1106. }
  1107. /* @class LatLng
  1108. * @aka L.LatLng
  1109. *
  1110. * Represents a geographical point with a certain latitude and longitude.
  1111. *
  1112. * @example
  1113. *
  1114. * ```
  1115. * var latlng = L.latLng(50.5, 30.5);
  1116. * ```
  1117. *
  1118. * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:
  1119. *
  1120. * ```
  1121. * map.panTo([50, 30]);
  1122. * map.panTo({lon: 30, lat: 50});
  1123. * map.panTo({lat: 50, lng: 30});
  1124. * map.panTo(L.latLng(50, 30));
  1125. * ```
  1126. *
  1127. * Note that `LatLng` does not inherit from Leaflet's `Class` object,
  1128. * which means new classes can't inherit from it, and new methods
  1129. * can't be added to it with the `include` function.
  1130. */
  1131. function LatLng(lat, lng, alt) {
  1132. if (isNaN(lat) || isNaN(lng)) {
  1133. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1134. }
  1135. // @property lat: Number
  1136. // Latitude in degrees
  1137. this.lat = +lat;
  1138. // @property lng: Number
  1139. // Longitude in degrees
  1140. this.lng = +lng;
  1141. // @property alt: Number
  1142. // Altitude in meters (optional)
  1143. if (alt !== undefined) {
  1144. this.alt = +alt;
  1145. }
  1146. }
  1147. LatLng.prototype = {
  1148. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1149. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.
  1150. equals: function (obj, maxMargin) {
  1151. if (!obj) { return false; }
  1152. obj = toLatLng(obj);
  1153. var margin = Math.max(
  1154. Math.abs(this.lat - obj.lat),
  1155. Math.abs(this.lng - obj.lng));
  1156. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1157. },
  1158. // @method toString(): String
  1159. // Returns a string representation of the point (for debugging purposes).
  1160. toString: function (precision) {
  1161. return 'LatLng(' +
  1162. formatNum(this.lat, precision) + ', ' +
  1163. formatNum(this.lng, precision) + ')';
  1164. },
  1165. // @method distanceTo(otherLatLng: LatLng): Number
  1166. // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
  1167. distanceTo: function (other) {
  1168. return Earth.distance(this, toLatLng(other));
  1169. },
  1170. // @method wrap(): LatLng
  1171. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1172. wrap: function () {
  1173. return Earth.wrapLatLng(this);
  1174. },
  1175. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1176. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1177. toBounds: function (sizeInMeters) {
  1178. var latAccuracy = 180 * sizeInMeters / 40075017,
  1179. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1180. return toLatLngBounds(
  1181. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1182. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1183. },
  1184. clone: function () {
  1185. return new LatLng(this.lat, this.lng, this.alt);
  1186. }
  1187. };
  1188. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1189. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1190. // @alternative
  1191. // @factory L.latLng(coords: Array): LatLng
  1192. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1193. // @alternative
  1194. // @factory L.latLng(coords: Object): LatLng
  1195. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1196. function toLatLng(a, b, c) {
  1197. if (a instanceof LatLng) {
  1198. return a;
  1199. }
  1200. if (isArray(a) && typeof a[0] !== 'object') {
  1201. if (a.length === 3) {
  1202. return new LatLng(a[0], a[1], a[2]);
  1203. }
  1204. if (a.length === 2) {
  1205. return new LatLng(a[0], a[1]);
  1206. }
  1207. return null;
  1208. }
  1209. if (a === undefined || a === null) {
  1210. return a;
  1211. }
  1212. if (typeof a === 'object' && 'lat' in a) {
  1213. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1214. }
  1215. if (b === undefined) {
  1216. return null;
  1217. }
  1218. return new LatLng(a, b, c);
  1219. }
  1220. /*
  1221. * @namespace CRS
  1222. * @crs L.CRS.Base
  1223. * Object that defines coordinate reference systems for projecting
  1224. * geographical points into pixel (screen) coordinates and back (and to
  1225. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1226. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1227. *
  1228. * Leaflet defines the most usual CRSs by default. If you want to use a
  1229. * CRS not defined by default, take a look at the
  1230. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1231. *
  1232. * Note that the CRS instances do not inherit from Leafet's `Class` object,
  1233. * and can't be instantiated. Also, new classes can't inherit from them,
  1234. * and methods can't be added to them with the `include` function.
  1235. */
  1236. var CRS = {
  1237. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1238. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1239. latLngToPoint: function (latlng, zoom) {
  1240. var projectedPoint = this.projection.project(latlng),
  1241. scale = this.scale(zoom);
  1242. return this.transformation._transform(projectedPoint, scale);
  1243. },
  1244. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1245. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1246. // zoom into geographical coordinates.
  1247. pointToLatLng: function (point, zoom) {
  1248. var scale = this.scale(zoom),
  1249. untransformedPoint = this.transformation.untransform(point, scale);
  1250. return this.projection.unproject(untransformedPoint);
  1251. },
  1252. // @method project(latlng: LatLng): Point
  1253. // Projects geographical coordinates into coordinates in units accepted for
  1254. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1255. project: function (latlng) {
  1256. return this.projection.project(latlng);
  1257. },
  1258. // @method unproject(point: Point): LatLng
  1259. // Given a projected coordinate returns the corresponding LatLng.
  1260. // The inverse of `project`.
  1261. unproject: function (point) {
  1262. return this.projection.unproject(point);
  1263. },
  1264. // @method scale(zoom: Number): Number
  1265. // Returns the scale used when transforming projected coordinates into
  1266. // pixel coordinates for a particular zoom. For example, it returns
  1267. // `256 * 2^zoom` for Mercator-based CRS.
  1268. scale: function (zoom) {
  1269. return 256 * Math.pow(2, zoom);
  1270. },
  1271. // @method zoom(scale: Number): Number
  1272. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1273. // factor of `scale`.
  1274. zoom: function (scale) {
  1275. return Math.log(scale / 256) / Math.LN2;
  1276. },
  1277. // @method getProjectedBounds(zoom: Number): Bounds
  1278. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1279. getProjectedBounds: function (zoom) {
  1280. if (this.infinite) { return null; }
  1281. var b = this.projection.bounds,
  1282. s = this.scale(zoom),
  1283. min = this.transformation.transform(b.min, s),
  1284. max = this.transformation.transform(b.max, s);
  1285. return new Bounds(min, max);
  1286. },
  1287. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1288. // Returns the distance between two geographical coordinates.
  1289. // @property code: String
  1290. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1291. //
  1292. // @property wrapLng: Number[]
  1293. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1294. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1295. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1296. //
  1297. // @property wrapLat: Number[]
  1298. // Like `wrapLng`, but for the latitude (vertical) axis.
  1299. // wrapLng: [min, max],
  1300. // wrapLat: [min, max],
  1301. // @property infinite: Boolean
  1302. // If true, the coordinate space will be unbounded (infinite in both axes)
  1303. infinite: false,
  1304. // @method wrapLatLng(latlng: LatLng): LatLng
  1305. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1306. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1307. wrapLatLng: function (latlng) {
  1308. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1309. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1310. alt = latlng.alt;
  1311. return new LatLng(lat, lng, alt);
  1312. },
  1313. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1314. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1315. // that its center is within the CRS's bounds.
  1316. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1317. wrapLatLngBounds: function (bounds) {
  1318. var center = bounds.getCenter(),
  1319. newCenter = this.wrapLatLng(center),
  1320. latShift = center.lat - newCenter.lat,
  1321. lngShift = center.lng - newCenter.lng;
  1322. if (latShift === 0 && lngShift === 0) {
  1323. return bounds;
  1324. }
  1325. var sw = bounds.getSouthWest(),
  1326. ne = bounds.getNorthEast(),
  1327. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1328. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1329. return new LatLngBounds(newSw, newNe);
  1330. }
  1331. };
  1332. /*
  1333. * @namespace CRS
  1334. * @crs L.CRS.Earth
  1335. *
  1336. * Serves as the base for CRS that are global such that they cover the earth.
  1337. * Can only be used as the base for other CRS and cannot be used directly,
  1338. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1339. * meters.
  1340. */
  1341. var Earth = extend({}, CRS, {
  1342. wrapLng: [-180, 180],
  1343. // Mean Earth Radius, as recommended for use by
  1344. // the International Union of Geodesy and Geophysics,
  1345. // see http://rosettacode.org/wiki/Haversine_formula
  1346. R: 6371000,
  1347. // distance between two geographical points using spherical law of cosines approximation
  1348. distance: function (latlng1, latlng2) {
  1349. var rad = Math.PI / 180,
  1350. lat1 = latlng1.lat * rad,
  1351. lat2 = latlng2.lat * rad,
  1352. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1353. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1354. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1355. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1356. return this.R * c;
  1357. }
  1358. });
  1359. /*
  1360. * @namespace Projection
  1361. * @projection L.Projection.SphericalMercator
  1362. *
  1363. * Spherical Mercator projection — the most common projection for online maps,
  1364. * used by almost all free and commercial tile providers. Assumes that Earth is
  1365. * a sphere. Used by the `EPSG:3857` CRS.
  1366. */
  1367. var earthRadius = 6378137;
  1368. var SphericalMercator = {
  1369. R: earthRadius,
  1370. MAX_LATITUDE: 85.0511287798,
  1371. project: function (latlng) {
  1372. var d = Math.PI / 180,
  1373. max = this.MAX_LATITUDE,
  1374. lat = Math.max(Math.min(max, latlng.lat), -max),
  1375. sin = Math.sin(lat * d);
  1376. return new Point(
  1377. this.R * latlng.lng * d,
  1378. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1379. },
  1380. unproject: function (point) {
  1381. var d = 180 / Math.PI;
  1382. return new LatLng(
  1383. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1384. point.x * d / this.R);
  1385. },
  1386. bounds: (function () {
  1387. var d = earthRadius * Math.PI;
  1388. return new Bounds([-d, -d], [d, d]);
  1389. })()
  1390. };
  1391. /*
  1392. * @class Transformation
  1393. * @aka L.Transformation
  1394. *
  1395. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1396. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1397. * the reverse. Used by Leaflet in its projections code.
  1398. *
  1399. * @example
  1400. *
  1401. * ```js
  1402. * var transformation = L.transformation(2, 5, -1, 10),
  1403. * p = L.point(1, 2),
  1404. * p2 = transformation.transform(p), // L.point(7, 8)
  1405. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1406. * ```
  1407. */
  1408. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1409. // Creates a `Transformation` object with the given coefficients.
  1410. function Transformation(a, b, c, d) {
  1411. if (isArray(a)) {
  1412. // use array properties
  1413. this._a = a[0];
  1414. this._b = a[1];
  1415. this._c = a[2];
  1416. this._d = a[3];
  1417. return;
  1418. }
  1419. this._a = a;
  1420. this._b = b;
  1421. this._c = c;
  1422. this._d = d;
  1423. }
  1424. Transformation.prototype = {
  1425. // @method transform(point: Point, scale?: Number): Point
  1426. // Returns a transformed point, optionally multiplied by the given scale.
  1427. // Only accepts actual `L.Point` instances, not arrays.
  1428. transform: function (point, scale) { // (Point, Number) -> Point
  1429. return this._transform(point.clone(), scale);
  1430. },
  1431. // destructive transform (faster)
  1432. _transform: function (point, scale) {
  1433. scale = scale || 1;
  1434. point.x = scale * (this._a * point.x + this._b);
  1435. point.y = scale * (this._c * point.y + this._d);
  1436. return point;
  1437. },
  1438. // @method untransform(point: Point, scale?: Number): Point
  1439. // Returns the reverse transformation of the given point, optionally divided
  1440. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1441. untransform: function (point, scale) {
  1442. scale = scale || 1;
  1443. return new Point(
  1444. (point.x / scale - this._b) / this._a,
  1445. (point.y / scale - this._d) / this._c);
  1446. }
  1447. };
  1448. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1449. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1450. // Instantiates a Transformation object with the given coefficients.
  1451. // @alternative
  1452. // @factory L.transformation(coefficients: Array): Transformation
  1453. // Expects an coefficients array of the form
  1454. // `[a: Number, b: Number, c: Number, d: Number]`.
  1455. function toTransformation(a, b, c, d) {
  1456. return new Transformation(a, b, c, d);
  1457. }
  1458. /*
  1459. * @namespace CRS
  1460. * @crs L.CRS.EPSG3857
  1461. *
  1462. * The most common CRS for online maps, used by almost all free and commercial
  1463. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1464. * Map's `crs` option.
  1465. */
  1466. var EPSG3857 = extend({}, Earth, {
  1467. code: 'EPSG:3857',
  1468. projection: SphericalMercator,
  1469. transformation: (function () {
  1470. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1471. return toTransformation(scale, 0.5, -scale, 0.5);
  1472. }())
  1473. });
  1474. var EPSG900913 = extend({}, EPSG3857, {
  1475. code: 'EPSG:900913'
  1476. });
  1477. // @namespace SVG; @section
  1478. // There are several static functions which can be called without instantiating L.SVG:
  1479. // @function create(name: String): SVGElement
  1480. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1481. // corresponding to the class name passed. For example, using 'line' will return
  1482. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1483. function svgCreate(name) {
  1484. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1485. }
  1486. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1487. // Generates a SVG path string for multiple rings, with each ring turning
  1488. // into "M..L..L.." instructions
  1489. function pointsToPath(rings, closed) {
  1490. var str = '',
  1491. i, j, len, len2, points, p;
  1492. for (i = 0, len = rings.length; i < len; i++) {
  1493. points = rings[i];
  1494. for (j = 0, len2 = points.length; j < len2; j++) {
  1495. p = points[j];
  1496. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1497. }
  1498. // closes the ring for polygons; "x" is VML syntax
  1499. str += closed ? (svg ? 'z' : 'x') : '';
  1500. }
  1501. // SVG complains about empty path strings
  1502. return str || 'M0 0';
  1503. }
  1504. /*
  1505. * @namespace Browser
  1506. * @aka L.Browser
  1507. *
  1508. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1509. *
  1510. * @example
  1511. *
  1512. * ```js
  1513. * if (L.Browser.ielt9) {
  1514. * alert('Upgrade your browser, dude!');
  1515. * }
  1516. * ```
  1517. */
  1518. var style$1 = document.documentElement.style;
  1519. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1520. var ie = 'ActiveXObject' in window;
  1521. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1522. var ielt9 = ie && !document.addEventListener;
  1523. // @property edge: Boolean; `true` for the Edge web browser.
  1524. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1525. // @property webkit: Boolean;
  1526. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1527. var webkit = userAgentContains('webkit');
  1528. // @property android: Boolean
  1529. // `true` for any browser running on an Android platform.
  1530. var android = userAgentContains('android');
  1531. // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
  1532. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1533. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1534. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1535. // @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome)
  1536. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1537. // @property opera: Boolean; `true` for the Opera browser
  1538. var opera = !!window.opera;
  1539. // @property chrome: Boolean; `true` for the Chrome browser.
  1540. var chrome = userAgentContains('chrome');
  1541. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1542. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1543. // @property safari: Boolean; `true` for the Safari browser.
  1544. var safari = !chrome && userAgentContains('safari');
  1545. var phantom = userAgentContains('phantom');
  1546. // @property opera12: Boolean
  1547. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1548. var opera12 = 'OTransition' in style$1;
  1549. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1550. var win = navigator.platform.indexOf('Win') === 0;
  1551. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1552. var ie3d = ie && ('transition' in style$1);
  1553. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1554. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1555. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1556. var gecko3d = 'MozPerspective' in style$1;
  1557. // @property any3d: Boolean
  1558. // `true` for all browsers supporting CSS transforms.
  1559. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1560. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1561. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1562. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1563. var mobileWebkit = mobile && webkit;
  1564. // @property mobileWebkit3d: Boolean
  1565. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1566. var mobileWebkit3d = mobile && webkit3d;
  1567. // @property msPointer: Boolean
  1568. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1569. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1570. // @property pointer: Boolean
  1571. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1572. var pointer = !!(window.PointerEvent || msPointer);
  1573. // @property touch: Boolean
  1574. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1575. // This does not necessarily mean that the browser is running in a computer with
  1576. // a touchscreen, it only means that the browser is capable of understanding
  1577. // touch events.
  1578. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  1579. (window.DocumentTouch && document instanceof window.DocumentTouch));
  1580. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1581. var mobileOpera = mobile && opera;
  1582. // @property mobileGecko: Boolean
  1583. // `true` for gecko-based browsers running in a mobile device.
  1584. var mobileGecko = mobile && gecko;
  1585. // @property retina: Boolean
  1586. // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
  1587. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1588. // @property canvas: Boolean
  1589. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1590. var canvas = (function () {
  1591. return !!document.createElement('canvas').getContext;
  1592. }());
  1593. // @property svg: Boolean
  1594. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1595. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1596. // @property vml: Boolean
  1597. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1598. var vml = !svg && (function () {
  1599. try {
  1600. var div = document.createElement('div');
  1601. div.innerHTML = '<v:shape adj="1"/>';
  1602. var shape = div.firstChild;
  1603. shape.style.behavior = 'url(#default#VML)';
  1604. return shape && (typeof shape.adj === 'object');
  1605. } catch (e) {
  1606. return false;
  1607. }
  1608. }());
  1609. function userAgentContains(str) {
  1610. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1611. }
  1612. var Browser = (Object.freeze || Object)({
  1613. ie: ie,
  1614. ielt9: ielt9,
  1615. edge: edge,
  1616. webkit: webkit,
  1617. android: android,
  1618. android23: android23,
  1619. androidStock: androidStock,
  1620. opera: opera,
  1621. chrome: chrome,
  1622. gecko: gecko,
  1623. safari: safari,
  1624. phantom: phantom,
  1625. opera12: opera12,
  1626. win: win,
  1627. ie3d: ie3d,
  1628. webkit3d: webkit3d,
  1629. gecko3d: gecko3d,
  1630. any3d: any3d,
  1631. mobile: mobile,
  1632. mobileWebkit: mobileWebkit,
  1633. mobileWebkit3d: mobileWebkit3d,
  1634. msPointer: msPointer,
  1635. pointer: pointer,
  1636. touch: touch,
  1637. mobileOpera: mobileOpera,
  1638. mobileGecko: mobileGecko,
  1639. retina: retina,
  1640. canvas: canvas,
  1641. svg: svg,
  1642. vml: vml
  1643. });
  1644. /*
  1645. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1646. */
  1647. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1648. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1649. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1650. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1651. var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
  1652. var _pointers = {};
  1653. var _pointerDocListener = false;
  1654. // DomEvent.DoubleTap needs to know about this
  1655. var _pointersCount = 0;
  1656. // Provides a touch events wrapper for (ms)pointer events.
  1657. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1658. function addPointerListener(obj, type, handler, id) {
  1659. if (type === 'touchstart') {
  1660. _addPointerStart(obj, handler, id);
  1661. } else if (type === 'touchmove') {
  1662. _addPointerMove(obj, handler, id);
  1663. } else if (type === 'touchend') {
  1664. _addPointerEnd(obj, handler, id);
  1665. }
  1666. return this;
  1667. }
  1668. function removePointerListener(obj, type, id) {
  1669. var handler = obj['_leaflet_' + type + id];
  1670. if (type === 'touchstart') {
  1671. obj.removeEventListener(POINTER_DOWN, handler, false);
  1672. } else if (type === 'touchmove') {
  1673. obj.removeEventListener(POINTER_MOVE, handler, false);
  1674. } else if (type === 'touchend') {
  1675. obj.removeEventListener(POINTER_UP, handler, false);
  1676. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1677. }
  1678. return this;
  1679. }
  1680. function _addPointerStart(obj, handler, id) {
  1681. var onDown = bind(function (e) {
  1682. if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  1683. // In IE11, some touch events needs to fire for form controls, or
  1684. // the controls will stop working. We keep a whitelist of tag names that
  1685. // need these events. For other target tags, we prevent default on the event.
  1686. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  1687. preventDefault(e);
  1688. } else {
  1689. return;
  1690. }
  1691. }
  1692. _handlePointer(e, handler);
  1693. });
  1694. obj['_leaflet_touchstart' + id] = onDown;
  1695. obj.addEventListener(POINTER_DOWN, onDown, false);
  1696. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1697. if (!_pointerDocListener) {
  1698. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  1699. document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1700. document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1701. document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
  1702. document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1703. _pointerDocListener = true;
  1704. }
  1705. }
  1706. function _globalPointerDown(e) {
  1707. _pointers[e.pointerId] = e;
  1708. _pointersCount++;
  1709. }
  1710. function _globalPointerMove(e) {
  1711. if (_pointers[e.pointerId]) {
  1712. _pointers[e.pointerId] = e;
  1713. }
  1714. }
  1715. function _globalPointerUp(e) {
  1716. delete _pointers[e.pointerId];
  1717. _pointersCount--;
  1718. }
  1719. function _handlePointer(e, handler) {
  1720. e.touches = [];
  1721. for (var i in _pointers) {
  1722. e.touches.push(_pointers[i]);
  1723. }
  1724. e.changedTouches = [e];
  1725. handler(e);
  1726. }
  1727. function _addPointerMove(obj, handler, id) {
  1728. var onMove = function (e) {
  1729. // don't fire touch moves when mouse isn't down
  1730. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  1731. _handlePointer(e, handler);
  1732. };
  1733. obj['_leaflet_touchmove' + id] = onMove;
  1734. obj.addEventListener(POINTER_MOVE, onMove, false);
  1735. }
  1736. function _addPointerEnd(obj, handler, id) {
  1737. var onUp = function (e) {
  1738. _handlePointer(e, handler);
  1739. };
  1740. obj['_leaflet_touchend' + id] = onUp;
  1741. obj.addEventListener(POINTER_UP, onUp, false);
  1742. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1743. }
  1744. /*
  1745. * Extends the event handling code with double tap support for mobile browsers.
  1746. */
  1747. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1748. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1749. var _pre = '_leaflet_';
  1750. // inspired by Zepto touch code by Thomas Fuchs
  1751. function addDoubleTapListener(obj, handler, id) {
  1752. var last, touch$$1,
  1753. doubleTap = false,
  1754. delay = 250;
  1755. function onTouchStart(e) {
  1756. var count;
  1757. if (pointer) {
  1758. if ((!edge) || e.pointerType === 'mouse') { return; }
  1759. count = _pointersCount;
  1760. } else {
  1761. count = e.touches.length;
  1762. }
  1763. if (count > 1) { return; }
  1764. var now = Date.now(),
  1765. delta = now - (last || now);
  1766. touch$$1 = e.touches ? e.touches[0] : e;
  1767. doubleTap = (delta > 0 && delta <= delay);
  1768. last = now;
  1769. }
  1770. function onTouchEnd(e) {
  1771. if (doubleTap && !touch$$1.cancelBubble) {
  1772. if (pointer) {
  1773. if ((!edge) || e.pointerType === 'mouse') { return; }
  1774. // work around .type being readonly with MSPointer* events
  1775. var newTouch = {},
  1776. prop, i;
  1777. for (i in touch$$1) {
  1778. prop = touch$$1[i];
  1779. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1780. }
  1781. touch$$1 = newTouch;
  1782. }
  1783. touch$$1.type = 'dblclick';
  1784. touch$$1.button = 0;
  1785. handler(touch$$1);
  1786. last = null;
  1787. }
  1788. }
  1789. obj[_pre + _touchstart + id] = onTouchStart;
  1790. obj[_pre + _touchend + id] = onTouchEnd;
  1791. obj[_pre + 'dblclick' + id] = handler;
  1792. obj.addEventListener(_touchstart, onTouchStart, false);
  1793. obj.addEventListener(_touchend, onTouchEnd, false);
  1794. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1795. // the browser doesn't fire touchend/pointerup events but does fire
  1796. // native dblclicks. See #4127.
  1797. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1798. obj.addEventListener('dblclick', handler, false);
  1799. return this;
  1800. }
  1801. function removeDoubleTapListener(obj, id) {
  1802. var touchstart = obj[_pre + _touchstart + id],
  1803. touchend = obj[_pre + _touchend + id],
  1804. dblclick = obj[_pre + 'dblclick' + id];
  1805. obj.removeEventListener(_touchstart, touchstart, false);
  1806. obj.removeEventListener(_touchend, touchend, false);
  1807. if (!edge) {
  1808. obj.removeEventListener('dblclick', dblclick, false);
  1809. }
  1810. return this;
  1811. }
  1812. /*
  1813. * @namespace DomUtil
  1814. *
  1815. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1816. * tree, used by Leaflet internally.
  1817. *
  1818. * Most functions expecting or returning a `HTMLElement` also work for
  1819. * SVG elements. The only difference is that classes refer to CSS classes
  1820. * in HTML and SVG classes in SVG.
  1821. */
  1822. // @property TRANSFORM: String
  1823. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1824. var TRANSFORM = testProp(
  1825. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1826. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1827. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1828. // @property TRANSITION: String
  1829. // Vendor-prefixed transition style name.
  1830. var TRANSITION = testProp(
  1831. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1832. // @property TRANSITION_END: String
  1833. // Vendor-prefixed transitionend event name.
  1834. var TRANSITION_END =
  1835. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1836. // @function get(id: String|HTMLElement): HTMLElement
  1837. // Returns an element given its DOM id, or returns the element itself
  1838. // if it was passed directly.
  1839. function get(id) {
  1840. return typeof id === 'string' ? document.getElementById(id) : id;
  1841. }
  1842. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1843. // Returns the value for a certain style attribute on an element,
  1844. // including computed values or values set through CSS.
  1845. function getStyle(el, style) {
  1846. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1847. if ((!value || value === 'auto') && document.defaultView) {
  1848. var css = document.defaultView.getComputedStyle(el, null);
  1849. value = css ? css[style] : null;
  1850. }
  1851. return value === 'auto' ? null : value;
  1852. }
  1853. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1854. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1855. function create$1(tagName, className, container) {
  1856. var el = document.createElement(tagName);
  1857. el.className = className || '';
  1858. if (container) {
  1859. container.appendChild(el);
  1860. }
  1861. return el;
  1862. }
  1863. // @function remove(el: HTMLElement)
  1864. // Removes `el` from its parent element
  1865. function remove(el) {
  1866. var parent = el.parentNode;
  1867. if (parent) {
  1868. parent.removeChild(el);
  1869. }
  1870. }
  1871. // @function empty(el: HTMLElement)
  1872. // Removes all of `el`'s children elements from `el`
  1873. function empty(el) {
  1874. while (el.firstChild) {
  1875. el.removeChild(el.firstChild);
  1876. }
  1877. }
  1878. // @function toFront(el: HTMLElement)
  1879. // Makes `el` the last child of its parent, so it renders in front of the other children.
  1880. function toFront(el) {
  1881. var parent = el.parentNode;
  1882. if (parent && parent.lastChild !== el) {
  1883. parent.appendChild(el);
  1884. }
  1885. }
  1886. // @function toBack(el: HTMLElement)
  1887. // Makes `el` the first child of its parent, so it renders behind the other children.
  1888. function toBack(el) {
  1889. var parent = el.parentNode;
  1890. if (parent && parent.firstChild !== el) {
  1891. parent.insertBefore(el, parent.firstChild);
  1892. }
  1893. }
  1894. // @function hasClass(el: HTMLElement, name: String): Boolean
  1895. // Returns `true` if the element's class attribute contains `name`.
  1896. function hasClass(el, name) {
  1897. if (el.classList !== undefined) {
  1898. return el.classList.contains(name);
  1899. }
  1900. var className = getClass(el);
  1901. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  1902. }
  1903. // @function addClass(el: HTMLElement, name: String)
  1904. // Adds `name` to the element's class attribute.
  1905. function addClass(el, name) {
  1906. if (el.classList !== undefined) {
  1907. var classes = splitWords(name);
  1908. for (var i = 0, len = classes.length; i < len; i++) {
  1909. el.classList.add(classes[i]);
  1910. }
  1911. } else if (!hasClass(el, name)) {
  1912. var className = getClass(el);
  1913. setClass(el, (className ? className + ' ' : '') + name);
  1914. }
  1915. }
  1916. // @function removeClass(el: HTMLElement, name: String)
  1917. // Removes `name` from the element's class attribute.
  1918. function removeClass(el, name) {
  1919. if (el.classList !== undefined) {
  1920. el.classList.remove(name);
  1921. } else {
  1922. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  1923. }
  1924. }
  1925. // @function setClass(el: HTMLElement, name: String)
  1926. // Sets the element's class.
  1927. function setClass(el, name) {
  1928. if (el.className.baseVal === undefined) {
  1929. el.className = name;
  1930. } else {
  1931. // in case of SVG element
  1932. el.className.baseVal = name;
  1933. }
  1934. }
  1935. // @function getClass(el: HTMLElement): String
  1936. // Returns the element's class.
  1937. function getClass(el) {
  1938. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  1939. // (Required for linked SVG elements in IE11.)
  1940. if (el.correspondingElement) {
  1941. el = el.correspondingElement;
  1942. }
  1943. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  1944. }
  1945. // @function setOpacity(el: HTMLElement, opacity: Number)
  1946. // Set the opacity of an element (including old IE support).
  1947. // `opacity` must be a number from `0` to `1`.
  1948. function setOpacity(el, value) {
  1949. if ('opacity' in el.style) {
  1950. el.style.opacity = value;
  1951. } else if ('filter' in el.style) {
  1952. _setOpacityIE(el, value);
  1953. }
  1954. }
  1955. function _setOpacityIE(el, value) {
  1956. var filter = false,
  1957. filterName = 'DXImageTransform.Microsoft.Alpha';
  1958. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  1959. try {
  1960. filter = el.filters.item(filterName);
  1961. } catch (e) {
  1962. // don't set opacity to 1 if we haven't already set an opacity,
  1963. // it isn't needed and breaks transparent pngs.
  1964. if (value === 1) { return; }
  1965. }
  1966. value = Math.round(value * 100);
  1967. if (filter) {
  1968. filter.Enabled = (value !== 100);
  1969. filter.Opacity = value;
  1970. } else {
  1971. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  1972. }
  1973. }
  1974. // @function testProp(props: String[]): String|false
  1975. // Goes through the array of style names and returns the first name
  1976. // that is a valid style name for an element. If no such name is found,
  1977. // it returns false. Useful for vendor-prefixed styles like `transform`.
  1978. function testProp(props) {
  1979. var style = document.documentElement.style;
  1980. for (var i = 0; i < props.length; i++) {
  1981. if (props[i] in style) {
  1982. return props[i];
  1983. }
  1984. }
  1985. return false;
  1986. }
  1987. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  1988. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  1989. // and optionally scaled by `scale`. Does not have an effect if the
  1990. // browser doesn't support 3D CSS transforms.
  1991. function setTransform(el, offset, scale) {
  1992. var pos = offset || new Point(0, 0);
  1993. el.style[TRANSFORM] =
  1994. (ie3d ?
  1995. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  1996. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  1997. (scale ? ' scale(' + scale + ')' : '');
  1998. }
  1999. // @function setPosition(el: HTMLElement, position: Point)
  2000. // Sets the position of `el` to coordinates specified by `position`,
  2001. // using CSS translate or top/left positioning depending on the browser
  2002. // (used by Leaflet internally to position its layers).
  2003. function setPosition(el, point) {
  2004. /*eslint-disable */
  2005. el._leaflet_pos = point;
  2006. /* eslint-enable */
  2007. if (any3d) {
  2008. setTransform(el, point);
  2009. } else {
  2010. el.style.left = point.x + 'px';
  2011. el.style.top = point.y + 'px';
  2012. }
  2013. }
  2014. // @function getPosition(el: HTMLElement): Point
  2015. // Returns the coordinates of an element previously positioned with setPosition.
  2016. function getPosition(el) {
  2017. // this method is only used for elements previously positioned using setPosition,
  2018. // so it's safe to cache the position for performance
  2019. return el._leaflet_pos || new Point(0, 0);
  2020. }
  2021. // @function disableTextSelection()
  2022. // Prevents the user from generating `selectstart` DOM events, usually generated
  2023. // when the user drags the mouse through a page with text. Used internally
  2024. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2025. // the map. Affects drag interactions on the whole document.
  2026. // @function enableTextSelection()
  2027. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2028. var disableTextSelection;
  2029. var enableTextSelection;
  2030. var _userSelect;
  2031. if ('onselectstart' in document) {
  2032. disableTextSelection = function () {
  2033. on(window, 'selectstart', preventDefault);
  2034. };
  2035. enableTextSelection = function () {
  2036. off(window, 'selectstart', preventDefault);
  2037. };
  2038. } else {
  2039. var userSelectProperty = testProp(
  2040. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2041. disableTextSelection = function () {
  2042. if (userSelectProperty) {
  2043. var style = document.documentElement.style;
  2044. _userSelect = style[userSelectProperty];
  2045. style[userSelectProperty] = 'none';
  2046. }
  2047. };
  2048. enableTextSelection = function () {
  2049. if (userSelectProperty) {
  2050. document.documentElement.style[userSelectProperty] = _userSelect;
  2051. _userSelect = undefined;
  2052. }
  2053. };
  2054. }
  2055. // @function disableImageDrag()
  2056. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2057. // for `dragstart` DOM events, usually generated when the user drags an image.
  2058. function disableImageDrag() {
  2059. on(window, 'dragstart', preventDefault);
  2060. }
  2061. // @function enableImageDrag()
  2062. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2063. function enableImageDrag() {
  2064. off(window, 'dragstart', preventDefault);
  2065. }
  2066. var _outlineElement;
  2067. var _outlineStyle;
  2068. // @function preventOutline(el: HTMLElement)
  2069. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2070. // of the element `el` invisible. Used internally by Leaflet to prevent
  2071. // focusable elements from displaying an outline when the user performs a
  2072. // drag interaction on them.
  2073. function preventOutline(element) {
  2074. while (element.tabIndex === -1) {
  2075. element = element.parentNode;
  2076. }
  2077. if (!element.style) { return; }
  2078. restoreOutline();
  2079. _outlineElement = element;
  2080. _outlineStyle = element.style.outline;
  2081. element.style.outline = 'none';
  2082. on(window, 'keydown', restoreOutline);
  2083. }
  2084. // @function restoreOutline()
  2085. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2086. function restoreOutline() {
  2087. if (!_outlineElement) { return; }
  2088. _outlineElement.style.outline = _outlineStyle;
  2089. _outlineElement = undefined;
  2090. _outlineStyle = undefined;
  2091. off(window, 'keydown', restoreOutline);
  2092. }
  2093. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2094. // Finds the closest parent node which size (width and height) is not null.
  2095. function getSizedParentNode(element) {
  2096. do {
  2097. element = element.parentNode;
  2098. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2099. return element;
  2100. }
  2101. // @function getScale(el: HTMLElement): Object
  2102. // Computes the CSS scale currently applied on the element.
  2103. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2104. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2105. function getScale(element) {
  2106. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2107. return {
  2108. x: rect.width / element.offsetWidth || 1,
  2109. y: rect.height / element.offsetHeight || 1,
  2110. boundingClientRect: rect
  2111. };
  2112. }
  2113. var DomUtil = (Object.freeze || Object)({
  2114. TRANSFORM: TRANSFORM,
  2115. TRANSITION: TRANSITION,
  2116. TRANSITION_END: TRANSITION_END,
  2117. get: get,
  2118. getStyle: getStyle,
  2119. create: create$1,
  2120. remove: remove,
  2121. empty: empty,
  2122. toFront: toFront,
  2123. toBack: toBack,
  2124. hasClass: hasClass,
  2125. addClass: addClass,
  2126. removeClass: removeClass,
  2127. setClass: setClass,
  2128. getClass: getClass,
  2129. setOpacity: setOpacity,
  2130. testProp: testProp,
  2131. setTransform: setTransform,
  2132. setPosition: setPosition,
  2133. getPosition: getPosition,
  2134. disableTextSelection: disableTextSelection,
  2135. enableTextSelection: enableTextSelection,
  2136. disableImageDrag: disableImageDrag,
  2137. enableImageDrag: enableImageDrag,
  2138. preventOutline: preventOutline,
  2139. restoreOutline: restoreOutline,
  2140. getSizedParentNode: getSizedParentNode,
  2141. getScale: getScale
  2142. });
  2143. /*
  2144. * @namespace DomEvent
  2145. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2146. */
  2147. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2148. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2149. // Adds a listener function (`fn`) to a particular DOM event type of the
  2150. // element `el`. You can optionally specify the context of the listener
  2151. // (object the `this` keyword will point to). You can also pass several
  2152. // space-separated types (e.g. `'click dblclick'`).
  2153. // @alternative
  2154. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2155. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2156. function on(obj, types, fn, context) {
  2157. if (typeof types === 'object') {
  2158. for (var type in types) {
  2159. addOne(obj, type, types[type], fn);
  2160. }
  2161. } else {
  2162. types = splitWords(types);
  2163. for (var i = 0, len = types.length; i < len; i++) {
  2164. addOne(obj, types[i], fn, context);
  2165. }
  2166. }
  2167. return this;
  2168. }
  2169. var eventsKey = '_leaflet_events';
  2170. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2171. // Removes a previously added listener function.
  2172. // Note that if you passed a custom context to on, you must pass the same
  2173. // context to `off` in order to remove the listener.
  2174. // @alternative
  2175. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2176. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2177. function off(obj, types, fn, context) {
  2178. if (typeof types === 'object') {
  2179. for (var type in types) {
  2180. removeOne(obj, type, types[type], fn);
  2181. }
  2182. } else if (types) {
  2183. types = splitWords(types);
  2184. for (var i = 0, len = types.length; i < len; i++) {
  2185. removeOne(obj, types[i], fn, context);
  2186. }
  2187. } else {
  2188. for (var j in obj[eventsKey]) {
  2189. removeOne(obj, j, obj[eventsKey][j]);
  2190. }
  2191. delete obj[eventsKey];
  2192. }
  2193. return this;
  2194. }
  2195. function addOne(obj, type, fn, context) {
  2196. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2197. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2198. var handler = function (e) {
  2199. return fn.call(context || obj, e || window.event);
  2200. };
  2201. var originalHandler = handler;
  2202. if (pointer && type.indexOf('touch') === 0) {
  2203. // Needs DomEvent.Pointer.js
  2204. addPointerListener(obj, type, handler, id);
  2205. } else if (touch && (type === 'dblclick') && addDoubleTapListener &&
  2206. !(pointer && chrome)) {
  2207. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  2208. // See #5180
  2209. addDoubleTapListener(obj, handler, id);
  2210. } else if ('addEventListener' in obj) {
  2211. if (type === 'mousewheel') {
  2212. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  2213. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  2214. handler = function (e) {
  2215. e = e || window.event;
  2216. if (isExternalTarget(obj, e)) {
  2217. originalHandler(e);
  2218. }
  2219. };
  2220. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  2221. } else {
  2222. if (type === 'click' && android) {
  2223. handler = function (e) {
  2224. filterClick(e, originalHandler);
  2225. };
  2226. }
  2227. obj.addEventListener(type, handler, false);
  2228. }
  2229. } else if ('attachEvent' in obj) {
  2230. obj.attachEvent('on' + type, handler);
  2231. }
  2232. obj[eventsKey] = obj[eventsKey] || {};
  2233. obj[eventsKey][id] = handler;
  2234. }
  2235. function removeOne(obj, type, fn, context) {
  2236. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  2237. handler = obj[eventsKey] && obj[eventsKey][id];
  2238. if (!handler) { return this; }
  2239. if (pointer && type.indexOf('touch') === 0) {
  2240. removePointerListener(obj, type, id);
  2241. } else if (touch && (type === 'dblclick') && removeDoubleTapListener &&
  2242. !(pointer && chrome)) {
  2243. removeDoubleTapListener(obj, id);
  2244. } else if ('removeEventListener' in obj) {
  2245. if (type === 'mousewheel') {
  2246. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  2247. } else {
  2248. obj.removeEventListener(
  2249. type === 'mouseenter' ? 'mouseover' :
  2250. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  2251. }
  2252. } else if ('detachEvent' in obj) {
  2253. obj.detachEvent('on' + type, handler);
  2254. }
  2255. obj[eventsKey][id] = null;
  2256. }
  2257. // @function stopPropagation(ev: DOMEvent): this
  2258. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2259. // ```js
  2260. // L.DomEvent.on(div, 'click', function (ev) {
  2261. // L.DomEvent.stopPropagation(ev);
  2262. // });
  2263. // ```
  2264. function stopPropagation(e) {
  2265. if (e.stopPropagation) {
  2266. e.stopPropagation();
  2267. } else if (e.originalEvent) { // In case of Leaflet event.
  2268. e.originalEvent._stopped = true;
  2269. } else {
  2270. e.cancelBubble = true;
  2271. }
  2272. skipped(e);
  2273. return this;
  2274. }
  2275. // @function disableScrollPropagation(el: HTMLElement): this
  2276. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  2277. function disableScrollPropagation(el) {
  2278. addOne(el, 'mousewheel', stopPropagation);
  2279. return this;
  2280. }
  2281. // @function disableClickPropagation(el: HTMLElement): this
  2282. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  2283. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2284. function disableClickPropagation(el) {
  2285. on(el, 'mousedown touchstart dblclick', stopPropagation);
  2286. addOne(el, 'click', fakeStop);
  2287. return this;
  2288. }
  2289. // @function preventDefault(ev: DOMEvent): this
  2290. // Prevents the default action of the DOM Event `ev` from happening (such as
  2291. // following a link in the href of the a element, or doing a POST request
  2292. // with page reload when a `<form>` is submitted).
  2293. // Use it inside listener functions.
  2294. function preventDefault(e) {
  2295. if (e.preventDefault) {
  2296. e.preventDefault();
  2297. } else {
  2298. e.returnValue = false;
  2299. }
  2300. return this;
  2301. }
  2302. // @function stop(ev: DOMEvent): this
  2303. // Does `stopPropagation` and `preventDefault` at the same time.
  2304. function stop(e) {
  2305. preventDefault(e);
  2306. stopPropagation(e);
  2307. return this;
  2308. }
  2309. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2310. // Gets normalized mouse position from a DOM event relative to the
  2311. // `container` (border excluded) or to the whole page if not specified.
  2312. function getMousePosition(e, container) {
  2313. if (!container) {
  2314. return new Point(e.clientX, e.clientY);
  2315. }
  2316. var scale = getScale(container),
  2317. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2318. return new Point(
  2319. // offset.left/top values are in page scale (like clientX/Y),
  2320. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2321. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2322. (e.clientY - offset.top) / scale.y - container.clientTop
  2323. );
  2324. }
  2325. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  2326. // and Firefox scrolls device pixels, not CSS pixels
  2327. var wheelPxFactor =
  2328. (win && chrome) ? 2 * window.devicePixelRatio :
  2329. gecko ? window.devicePixelRatio : 1;
  2330. // @function getWheelDelta(ev: DOMEvent): Number
  2331. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  2332. // pixels scrolled (negative if scrolling down).
  2333. // Events from pointing devices without precise scrolling are mapped to
  2334. // a best guess of 60 pixels.
  2335. function getWheelDelta(e) {
  2336. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2337. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2338. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2339. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2340. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2341. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2342. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2343. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2344. 0;
  2345. }
  2346. var skipEvents = {};
  2347. function fakeStop(e) {
  2348. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  2349. skipEvents[e.type] = true;
  2350. }
  2351. function skipped(e) {
  2352. var events = skipEvents[e.type];
  2353. // reset when checking, as it's only used in map container and propagates outside of the map
  2354. skipEvents[e.type] = false;
  2355. return events;
  2356. }
  2357. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2358. function isExternalTarget(el, e) {
  2359. var related = e.relatedTarget;
  2360. if (!related) { return true; }
  2361. try {
  2362. while (related && (related !== el)) {
  2363. related = related.parentNode;
  2364. }
  2365. } catch (err) {
  2366. return false;
  2367. }
  2368. return (related !== el);
  2369. }
  2370. var lastClick;
  2371. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  2372. function filterClick(e, handler) {
  2373. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  2374. elapsed = lastClick && (timeStamp - lastClick);
  2375. // are they closer together than 500ms yet more than 100ms?
  2376. // Android typically triggers them ~300ms apart while multiple listeners
  2377. // on the same event should be triggered far faster;
  2378. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2379. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2380. stop(e);
  2381. return;
  2382. }
  2383. lastClick = timeStamp;
  2384. handler(e);
  2385. }
  2386. var DomEvent = (Object.freeze || Object)({
  2387. on: on,
  2388. off: off,
  2389. stopPropagation: stopPropagation,
  2390. disableScrollPropagation: disableScrollPropagation,
  2391. disableClickPropagation: disableClickPropagation,
  2392. preventDefault: preventDefault,
  2393. stop: stop,
  2394. getMousePosition: getMousePosition,
  2395. getWheelDelta: getWheelDelta,
  2396. fakeStop: fakeStop,
  2397. skipped: skipped,
  2398. isExternalTarget: isExternalTarget,
  2399. addListener: on,
  2400. removeListener: off
  2401. });
  2402. /*
  2403. * @class PosAnimation
  2404. * @aka L.PosAnimation
  2405. * @inherits Evented
  2406. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2407. *
  2408. * @example
  2409. * ```js
  2410. * var fx = new L.PosAnimation();
  2411. * fx.run(el, [300, 500], 0.5);
  2412. * ```
  2413. *
  2414. * @constructor L.PosAnimation()
  2415. * Creates a `PosAnimation` object.
  2416. *
  2417. */
  2418. var PosAnimation = Evented.extend({
  2419. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2420. // Run an animation of a given element to a new position, optionally setting
  2421. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2422. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2423. // `0.5` by default).
  2424. run: function (el, newPos, duration, easeLinearity) {
  2425. this.stop();
  2426. this._el = el;
  2427. this._inProgress = true;
  2428. this._duration = duration || 0.25;
  2429. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2430. this._startPos = getPosition(el);
  2431. this._offset = newPos.subtract(this._startPos);
  2432. this._startTime = +new Date();
  2433. // @event start: Event
  2434. // Fired when the animation starts
  2435. this.fire('start');
  2436. this._animate();
  2437. },
  2438. // @method stop()
  2439. // Stops the animation (if currently running).
  2440. stop: function () {
  2441. if (!this._inProgress) { return; }
  2442. this._step(true);
  2443. this._complete();
  2444. },
  2445. _animate: function () {
  2446. // animation loop
  2447. this._animId = requestAnimFrame(this._animate, this);
  2448. this._step();
  2449. },
  2450. _step: function (round) {
  2451. var elapsed = (+new Date()) - this._startTime,
  2452. duration = this._duration * 1000;
  2453. if (elapsed < duration) {
  2454. this._runFrame(this._easeOut(elapsed / duration), round);
  2455. } else {
  2456. this._runFrame(1);
  2457. this._complete();
  2458. }
  2459. },
  2460. _runFrame: function (progress, round) {
  2461. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2462. if (round) {
  2463. pos._round();
  2464. }
  2465. setPosition(this._el, pos);
  2466. // @event step: Event
  2467. // Fired continuously during the animation.
  2468. this.fire('step');
  2469. },
  2470. _complete: function () {
  2471. cancelAnimFrame(this._animId);
  2472. this._inProgress = false;
  2473. // @event end: Event
  2474. // Fired when the animation ends.
  2475. this.fire('end');
  2476. },
  2477. _easeOut: function (t) {
  2478. return 1 - Math.pow(1 - t, this._easeOutPower);
  2479. }
  2480. });
  2481. /*
  2482. * @class Map
  2483. * @aka L.Map
  2484. * @inherits Evented
  2485. *
  2486. * The central class of the API — it is used to create a map on a page and manipulate it.
  2487. *
  2488. * @example
  2489. *
  2490. * ```js
  2491. * // initialize the map on the "map" div with a given center and zoom
  2492. * var map = L.map('map', {
  2493. * center: [51.505, -0.09],
  2494. * zoom: 13
  2495. * });
  2496. * ```
  2497. *
  2498. */
  2499. var Map = Evented.extend({
  2500. options: {
  2501. // @section Map State Options
  2502. // @option crs: CRS = L.CRS.EPSG3857
  2503. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2504. // sure what it means.
  2505. crs: EPSG3857,
  2506. // @option center: LatLng = undefined
  2507. // Initial geographic center of the map
  2508. center: undefined,
  2509. // @option zoom: Number = undefined
  2510. // Initial map zoom level
  2511. zoom: undefined,
  2512. // @option minZoom: Number = *
  2513. // Minimum zoom level of the map.
  2514. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2515. // the lowest of their `minZoom` options will be used instead.
  2516. minZoom: undefined,
  2517. // @option maxZoom: Number = *
  2518. // Maximum zoom level of the map.
  2519. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2520. // the highest of their `maxZoom` options will be used instead.
  2521. maxZoom: undefined,
  2522. // @option layers: Layer[] = []
  2523. // Array of layers that will be added to the map initially
  2524. layers: [],
  2525. // @option maxBounds: LatLngBounds = null
  2526. // When this option is set, the map restricts the view to the given
  2527. // geographical bounds, bouncing the user back if the user tries to pan
  2528. // outside the view. To set the restriction dynamically, use
  2529. // [`setMaxBounds`](#map-setmaxbounds) method.
  2530. maxBounds: undefined,
  2531. // @option renderer: Renderer = *
  2532. // The default method for drawing vector layers on the map. `L.SVG`
  2533. // or `L.Canvas` by default depending on browser support.
  2534. renderer: undefined,
  2535. // @section Animation Options
  2536. // @option zoomAnimation: Boolean = true
  2537. // Whether the map zoom animation is enabled. By default it's enabled
  2538. // in all browsers that support CSS3 Transitions except Android.
  2539. zoomAnimation: true,
  2540. // @option zoomAnimationThreshold: Number = 4
  2541. // Won't animate zoom if the zoom difference exceeds this value.
  2542. zoomAnimationThreshold: 4,
  2543. // @option fadeAnimation: Boolean = true
  2544. // Whether the tile fade animation is enabled. By default it's enabled
  2545. // in all browsers that support CSS3 Transitions except Android.
  2546. fadeAnimation: true,
  2547. // @option markerZoomAnimation: Boolean = true
  2548. // Whether markers animate their zoom with the zoom animation, if disabled
  2549. // they will disappear for the length of the animation. By default it's
  2550. // enabled in all browsers that support CSS3 Transitions except Android.
  2551. markerZoomAnimation: true,
  2552. // @option transform3DLimit: Number = 2^23
  2553. // Defines the maximum size of a CSS translation transform. The default
  2554. // value should not be changed unless a web browser positions layers in
  2555. // the wrong place after doing a large `panBy`.
  2556. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2557. // @section Interaction Options
  2558. // @option zoomSnap: Number = 1
  2559. // Forces the map's zoom level to always be a multiple of this, particularly
  2560. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2561. // By default, the zoom level snaps to the nearest integer; lower values
  2562. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2563. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2564. zoomSnap: 1,
  2565. // @option zoomDelta: Number = 1
  2566. // Controls how much the map's zoom level will change after a
  2567. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2568. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2569. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2570. zoomDelta: 1,
  2571. // @option trackResize: Boolean = true
  2572. // Whether the map automatically handles browser window resize to update itself.
  2573. trackResize: true
  2574. },
  2575. initialize: function (id, options) { // (HTMLElement or String, Object)
  2576. options = setOptions(this, options);
  2577. // Make sure to assign internal flags at the beginning,
  2578. // to avoid inconsistent state in some edge cases.
  2579. this._handlers = [];
  2580. this._layers = {};
  2581. this._zoomBoundLayers = {};
  2582. this._sizeChanged = true;
  2583. this._initContainer(id);
  2584. this._initLayout();
  2585. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2586. this._onResize = bind(this._onResize, this);
  2587. this._initEvents();
  2588. if (options.maxBounds) {
  2589. this.setMaxBounds(options.maxBounds);
  2590. }
  2591. if (options.zoom !== undefined) {
  2592. this._zoom = this._limitZoom(options.zoom);
  2593. }
  2594. if (options.center && options.zoom !== undefined) {
  2595. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2596. }
  2597. this.callInitHooks();
  2598. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2599. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2600. this.options.zoomAnimation;
  2601. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2602. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2603. if (this._zoomAnimated) {
  2604. this._createAnimProxy();
  2605. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2606. }
  2607. this._addLayers(this.options.layers);
  2608. },
  2609. // @section Methods for modifying map state
  2610. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2611. // Sets the view of the map (geographical center and zoom) with the given
  2612. // animation options.
  2613. setView: function (center, zoom, options) {
  2614. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2615. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2616. options = options || {};
  2617. this._stop();
  2618. if (this._loaded && !options.reset && options !== true) {
  2619. if (options.animate !== undefined) {
  2620. options.zoom = extend({animate: options.animate}, options.zoom);
  2621. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2622. }
  2623. // try animating pan or zoom
  2624. var moved = (this._zoom !== zoom) ?
  2625. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2626. this._tryAnimatedPan(center, options.pan);
  2627. if (moved) {
  2628. // prevent resize handler call, the view will refresh after animation anyway
  2629. clearTimeout(this._sizeTimer);
  2630. return this;
  2631. }
  2632. }
  2633. // animation didn't start, just reset the map view
  2634. this._resetView(center, zoom);
  2635. return this;
  2636. },
  2637. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2638. // Sets the zoom of the map.
  2639. setZoom: function (zoom, options) {
  2640. if (!this._loaded) {
  2641. this._zoom = zoom;
  2642. return this;
  2643. }
  2644. return this.setView(this.getCenter(), zoom, {zoom: options});
  2645. },
  2646. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2647. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2648. zoomIn: function (delta, options) {
  2649. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2650. return this.setZoom(this._zoom + delta, options);
  2651. },
  2652. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2653. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2654. zoomOut: function (delta, options) {
  2655. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2656. return this.setZoom(this._zoom - delta, options);
  2657. },
  2658. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2659. // Zooms the map while keeping a specified geographical point on the map
  2660. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2661. // @alternative
  2662. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2663. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2664. setZoomAround: function (latlng, zoom, options) {
  2665. var scale = this.getZoomScale(zoom),
  2666. viewHalf = this.getSize().divideBy(2),
  2667. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2668. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2669. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2670. return this.setView(newCenter, zoom, {zoom: options});
  2671. },
  2672. _getBoundsCenterZoom: function (bounds, options) {
  2673. options = options || {};
  2674. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2675. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2676. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2677. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2678. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2679. if (zoom === Infinity) {
  2680. return {
  2681. center: bounds.getCenter(),
  2682. zoom: zoom
  2683. };
  2684. }
  2685. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2686. swPoint = this.project(bounds.getSouthWest(), zoom),
  2687. nePoint = this.project(bounds.getNorthEast(), zoom),
  2688. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2689. return {
  2690. center: center,
  2691. zoom: zoom
  2692. };
  2693. },
  2694. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2695. // Sets a map view that contains the given geographical bounds with the
  2696. // maximum zoom level possible.
  2697. fitBounds: function (bounds, options) {
  2698. bounds = toLatLngBounds(bounds);
  2699. if (!bounds.isValid()) {
  2700. throw new Error('Bounds are not valid.');
  2701. }
  2702. var target = this._getBoundsCenterZoom(bounds, options);
  2703. return this.setView(target.center, target.zoom, options);
  2704. },
  2705. // @method fitWorld(options?: fitBounds options): this
  2706. // Sets a map view that mostly contains the whole world with the maximum
  2707. // zoom level possible.
  2708. fitWorld: function (options) {
  2709. return this.fitBounds([[-90, -180], [90, 180]], options);
  2710. },
  2711. // @method panTo(latlng: LatLng, options?: Pan options): this
  2712. // Pans the map to a given center.
  2713. panTo: function (center, options) { // (LatLng)
  2714. return this.setView(center, this._zoom, {pan: options});
  2715. },
  2716. // @method panBy(offset: Point, options?: Pan options): this
  2717. // Pans the map by a given number of pixels (animated).
  2718. panBy: function (offset, options) {
  2719. offset = toPoint(offset).round();
  2720. options = options || {};
  2721. if (!offset.x && !offset.y) {
  2722. return this.fire('moveend');
  2723. }
  2724. // If we pan too far, Chrome gets issues with tiles
  2725. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2726. if (options.animate !== true && !this.getSize().contains(offset)) {
  2727. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2728. return this;
  2729. }
  2730. if (!this._panAnim) {
  2731. this._panAnim = new PosAnimation();
  2732. this._panAnim.on({
  2733. 'step': this._onPanTransitionStep,
  2734. 'end': this._onPanTransitionEnd
  2735. }, this);
  2736. }
  2737. // don't fire movestart if animating inertia
  2738. if (!options.noMoveStart) {
  2739. this.fire('movestart');
  2740. }
  2741. // animate pan unless animate: false specified
  2742. if (options.animate !== false) {
  2743. addClass(this._mapPane, 'leaflet-pan-anim');
  2744. var newPos = this._getMapPanePos().subtract(offset).round();
  2745. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2746. } else {
  2747. this._rawPanBy(offset);
  2748. this.fire('move').fire('moveend');
  2749. }
  2750. return this;
  2751. },
  2752. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2753. // Sets the view of the map (geographical center and zoom) performing a smooth
  2754. // pan-zoom animation.
  2755. flyTo: function (targetCenter, targetZoom, options) {
  2756. options = options || {};
  2757. if (options.animate === false || !any3d) {
  2758. return this.setView(targetCenter, targetZoom, options);
  2759. }
  2760. this._stop();
  2761. var from = this.project(this.getCenter()),
  2762. to = this.project(targetCenter),
  2763. size = this.getSize(),
  2764. startZoom = this._zoom;
  2765. targetCenter = toLatLng(targetCenter);
  2766. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2767. var w0 = Math.max(size.x, size.y),
  2768. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2769. u1 = (to.distanceTo(from)) || 1,
  2770. rho = 1.42,
  2771. rho2 = rho * rho;
  2772. function r(i) {
  2773. var s1 = i ? -1 : 1,
  2774. s2 = i ? w1 : w0,
  2775. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2776. b1 = 2 * s2 * rho2 * u1,
  2777. b = t1 / b1,
  2778. sq = Math.sqrt(b * b + 1) - b;
  2779. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2780. // thus triggering an infinite loop in flyTo
  2781. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2782. return log;
  2783. }
  2784. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2785. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2786. function tanh(n) { return sinh(n) / cosh(n); }
  2787. var r0 = r(0);
  2788. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2789. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2790. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2791. var start = Date.now(),
  2792. S = (r(1) - r0) / rho,
  2793. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2794. function frame() {
  2795. var t = (Date.now() - start) / duration,
  2796. s = easeOut(t) * S;
  2797. if (t <= 1) {
  2798. this._flyToFrame = requestAnimFrame(frame, this);
  2799. this._move(
  2800. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2801. this.getScaleZoom(w0 / w(s), startZoom),
  2802. {flyTo: true});
  2803. } else {
  2804. this
  2805. ._move(targetCenter, targetZoom)
  2806. ._moveEnd(true);
  2807. }
  2808. }
  2809. this._moveStart(true, options.noMoveStart);
  2810. frame.call(this);
  2811. return this;
  2812. },
  2813. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2814. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2815. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2816. flyToBounds: function (bounds, options) {
  2817. var target = this._getBoundsCenterZoom(bounds, options);
  2818. return this.flyTo(target.center, target.zoom, options);
  2819. },
  2820. // @method setMaxBounds(bounds: Bounds): this
  2821. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2822. setMaxBounds: function (bounds) {
  2823. bounds = toLatLngBounds(bounds);
  2824. if (!bounds.isValid()) {
  2825. this.options.maxBounds = null;
  2826. return this.off('moveend', this._panInsideMaxBounds);
  2827. } else if (this.options.maxBounds) {
  2828. this.off('moveend', this._panInsideMaxBounds);
  2829. }
  2830. this.options.maxBounds = bounds;
  2831. if (this._loaded) {
  2832. this._panInsideMaxBounds();
  2833. }
  2834. return this.on('moveend', this._panInsideMaxBounds);
  2835. },
  2836. // @method setMinZoom(zoom: Number): this
  2837. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2838. setMinZoom: function (zoom) {
  2839. var oldZoom = this.options.minZoom;
  2840. this.options.minZoom = zoom;
  2841. if (this._loaded && oldZoom !== zoom) {
  2842. this.fire('zoomlevelschange');
  2843. if (this.getZoom() < this.options.minZoom) {
  2844. return this.setZoom(zoom);
  2845. }
  2846. }
  2847. return this;
  2848. },
  2849. // @method setMaxZoom(zoom: Number): this
  2850. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2851. setMaxZoom: function (zoom) {
  2852. var oldZoom = this.options.maxZoom;
  2853. this.options.maxZoom = zoom;
  2854. if (this._loaded && oldZoom !== zoom) {
  2855. this.fire('zoomlevelschange');
  2856. if (this.getZoom() > this.options.maxZoom) {
  2857. return this.setZoom(zoom);
  2858. }
  2859. }
  2860. return this;
  2861. },
  2862. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2863. // Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.
  2864. panInsideBounds: function (bounds, options) {
  2865. this._enforcingBounds = true;
  2866. var center = this.getCenter(),
  2867. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2868. if (!center.equals(newCenter)) {
  2869. this.panTo(newCenter, options);
  2870. }
  2871. this._enforcingBounds = false;
  2872. return this;
  2873. },
  2874. // @method panInside(latlng: LatLng, options?: options): this
  2875. // Pans the map the minimum amount to make the `latlng` visible. Use
  2876. // `padding`, `paddingTopLeft` and `paddingTopRight` options to fit
  2877. // the display to more restricted bounds, like [`fitBounds`](#map-fitbounds).
  2878. // If `latlng` is already within the (optionally padded) display bounds,
  2879. // the map will not be panned.
  2880. panInside: function (latlng, options) {
  2881. options = options || {};
  2882. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2883. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2884. center = this.getCenter(),
  2885. pixelCenter = this.project(center),
  2886. pixelPoint = this.project(latlng),
  2887. pixelBounds = this.getPixelBounds(),
  2888. halfPixelBounds = pixelBounds.getSize().divideBy(2),
  2889. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]);
  2890. if (!paddedBounds.contains(pixelPoint)) {
  2891. this._enforcingBounds = true;
  2892. var diff = pixelCenter.subtract(pixelPoint),
  2893. newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y);
  2894. if (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) {
  2895. newCenter.x = pixelCenter.x - diff.x;
  2896. if (diff.x > 0) {
  2897. newCenter.x += halfPixelBounds.x - paddingTL.x;
  2898. } else {
  2899. newCenter.x -= halfPixelBounds.x - paddingBR.x;
  2900. }
  2901. }
  2902. if (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) {
  2903. newCenter.y = pixelCenter.y - diff.y;
  2904. if (diff.y > 0) {
  2905. newCenter.y += halfPixelBounds.y - paddingTL.y;
  2906. } else {
  2907. newCenter.y -= halfPixelBounds.y - paddingBR.y;
  2908. }
  2909. }
  2910. this.panTo(this.unproject(newCenter), options);
  2911. this._enforcingBounds = false;
  2912. }
  2913. return this;
  2914. },
  2915. // @method invalidateSize(options: Zoom/pan options): this
  2916. // Checks if the map container size changed and updates the map if so —
  2917. // call it after you've changed the map size dynamically, also animating
  2918. // pan by default. If `options.pan` is `false`, panning will not occur.
  2919. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2920. // that it doesn't happen often even if the method is called many
  2921. // times in a row.
  2922. // @alternative
  2923. // @method invalidateSize(animate: Boolean): this
  2924. // Checks if the map container size changed and updates the map if so —
  2925. // call it after you've changed the map size dynamically, also animating
  2926. // pan by default.
  2927. invalidateSize: function (options) {
  2928. if (!this._loaded) { return this; }
  2929. options = extend({
  2930. animate: false,
  2931. pan: true
  2932. }, options === true ? {animate: true} : options);
  2933. var oldSize = this.getSize();
  2934. this._sizeChanged = true;
  2935. this._lastCenter = null;
  2936. var newSize = this.getSize(),
  2937. oldCenter = oldSize.divideBy(2).round(),
  2938. newCenter = newSize.divideBy(2).round(),
  2939. offset = oldCenter.subtract(newCenter);
  2940. if (!offset.x && !offset.y) { return this; }
  2941. if (options.animate && options.pan) {
  2942. this.panBy(offset);
  2943. } else {
  2944. if (options.pan) {
  2945. this._rawPanBy(offset);
  2946. }
  2947. this.fire('move');
  2948. if (options.debounceMoveend) {
  2949. clearTimeout(this._sizeTimer);
  2950. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2951. } else {
  2952. this.fire('moveend');
  2953. }
  2954. }
  2955. // @section Map state change events
  2956. // @event resize: ResizeEvent
  2957. // Fired when the map is resized.
  2958. return this.fire('resize', {
  2959. oldSize: oldSize,
  2960. newSize: newSize
  2961. });
  2962. },
  2963. // @section Methods for modifying map state
  2964. // @method stop(): this
  2965. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2966. stop: function () {
  2967. this.setZoom(this._limitZoom(this._zoom));
  2968. if (!this.options.zoomSnap) {
  2969. this.fire('viewreset');
  2970. }
  2971. return this._stop();
  2972. },
  2973. // @section Geolocation methods
  2974. // @method locate(options?: Locate options): this
  2975. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2976. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2977. // and optionally sets the map view to the user's location with respect to
  2978. // detection accuracy (or to the world view if geolocation failed).
  2979. // Note that, if your page doesn't use HTTPS, this method will fail in
  2980. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2981. // See `Locate options` for more details.
  2982. locate: function (options) {
  2983. options = this._locateOptions = extend({
  2984. timeout: 10000,
  2985. watch: false
  2986. // setView: false
  2987. // maxZoom: <Number>
  2988. // maximumAge: 0
  2989. // enableHighAccuracy: false
  2990. }, options);
  2991. if (!('geolocation' in navigator)) {
  2992. this._handleGeolocationError({
  2993. code: 0,
  2994. message: 'Geolocation not supported.'
  2995. });
  2996. return this;
  2997. }
  2998. var onResponse = bind(this._handleGeolocationResponse, this),
  2999. onError = bind(this._handleGeolocationError, this);
  3000. if (options.watch) {
  3001. this._locationWatchId =
  3002. navigator.geolocation.watchPosition(onResponse, onError, options);
  3003. } else {
  3004. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  3005. }
  3006. return this;
  3007. },
  3008. // @method stopLocate(): this
  3009. // Stops watching location previously initiated by `map.locate({watch: true})`
  3010. // and aborts resetting the map view if map.locate was called with
  3011. // `{setView: true}`.
  3012. stopLocate: function () {
  3013. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3014. navigator.geolocation.clearWatch(this._locationWatchId);
  3015. }
  3016. if (this._locateOptions) {
  3017. this._locateOptions.setView = false;
  3018. }
  3019. return this;
  3020. },
  3021. _handleGeolocationError: function (error) {
  3022. var c = error.code,
  3023. message = error.message ||
  3024. (c === 1 ? 'permission denied' :
  3025. (c === 2 ? 'position unavailable' : 'timeout'));
  3026. if (this._locateOptions.setView && !this._loaded) {
  3027. this.fitWorld();
  3028. }
  3029. // @section Location events
  3030. // @event locationerror: ErrorEvent
  3031. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3032. this.fire('locationerror', {
  3033. code: c,
  3034. message: 'Geolocation error: ' + message + '.'
  3035. });
  3036. },
  3037. _handleGeolocationResponse: function (pos) {
  3038. var lat = pos.coords.latitude,
  3039. lng = pos.coords.longitude,
  3040. latlng = new LatLng(lat, lng),
  3041. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3042. options = this._locateOptions;
  3043. if (options.setView) {
  3044. var zoom = this.getBoundsZoom(bounds);
  3045. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3046. }
  3047. var data = {
  3048. latlng: latlng,
  3049. bounds: bounds,
  3050. timestamp: pos.timestamp
  3051. };
  3052. for (var i in pos.coords) {
  3053. if (typeof pos.coords[i] === 'number') {
  3054. data[i] = pos.coords[i];
  3055. }
  3056. }
  3057. // @event locationfound: LocationEvent
  3058. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3059. // went successfully.
  3060. this.fire('locationfound', data);
  3061. },
  3062. // TODO Appropriate docs section?
  3063. // @section Other Methods
  3064. // @method addHandler(name: String, HandlerClass: Function): this
  3065. // Adds a new `Handler` to the map, given its name and constructor function.
  3066. addHandler: function (name, HandlerClass) {
  3067. if (!HandlerClass) { return this; }
  3068. var handler = this[name] = new HandlerClass(this);
  3069. this._handlers.push(handler);
  3070. if (this.options[name]) {
  3071. handler.enable();
  3072. }
  3073. return this;
  3074. },
  3075. // @method remove(): this
  3076. // Destroys the map and clears all related event listeners.
  3077. remove: function () {
  3078. this._initEvents(true);
  3079. if (this._containerId !== this._container._leaflet_id) {
  3080. throw new Error('Map container is being reused by another instance');
  3081. }
  3082. try {
  3083. // throws error in IE6-8
  3084. delete this._container._leaflet_id;
  3085. delete this._containerId;
  3086. } catch (e) {
  3087. /*eslint-disable */
  3088. this._container._leaflet_id = undefined;
  3089. /* eslint-enable */
  3090. this._containerId = undefined;
  3091. }
  3092. if (this._locationWatchId !== undefined) {
  3093. this.stopLocate();
  3094. }
  3095. this._stop();
  3096. remove(this._mapPane);
  3097. if (this._clearControlPos) {
  3098. this._clearControlPos();
  3099. }
  3100. if (this._resizeRequest) {
  3101. cancelAnimFrame(this._resizeRequest);
  3102. this._resizeRequest = null;
  3103. }
  3104. this._clearHandlers();
  3105. if (this._loaded) {
  3106. // @section Map state change events
  3107. // @event unload: Event
  3108. // Fired when the map is destroyed with [remove](#map-remove) method.
  3109. this.fire('unload');
  3110. }
  3111. var i;
  3112. for (i in this._layers) {
  3113. this._layers[i].remove();
  3114. }
  3115. for (i in this._panes) {
  3116. remove(this._panes[i]);
  3117. }
  3118. this._layers = [];
  3119. this._panes = [];
  3120. delete this._mapPane;
  3121. delete this._renderer;
  3122. return this;
  3123. },
  3124. // @section Other Methods
  3125. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3126. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3127. // then returns it. The pane is created as a child of `container`, or
  3128. // as a child of the main map pane if not set.
  3129. createPane: function (name, container) {
  3130. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3131. pane = create$1('div', className, container || this._mapPane);
  3132. if (name) {
  3133. this._panes[name] = pane;
  3134. }
  3135. return pane;
  3136. },
  3137. // @section Methods for Getting Map State
  3138. // @method getCenter(): LatLng
  3139. // Returns the geographical center of the map view
  3140. getCenter: function () {
  3141. this._checkIfLoaded();
  3142. if (this._lastCenter && !this._moved()) {
  3143. return this._lastCenter;
  3144. }
  3145. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3146. },
  3147. // @method getZoom(): Number
  3148. // Returns the current zoom level of the map view
  3149. getZoom: function () {
  3150. return this._zoom;
  3151. },
  3152. // @method getBounds(): LatLngBounds
  3153. // Returns the geographical bounds visible in the current map view
  3154. getBounds: function () {
  3155. var bounds = this.getPixelBounds(),
  3156. sw = this.unproject(bounds.getBottomLeft()),
  3157. ne = this.unproject(bounds.getTopRight());
  3158. return new LatLngBounds(sw, ne);
  3159. },
  3160. // @method getMinZoom(): Number
  3161. // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.
  3162. getMinZoom: function () {
  3163. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3164. },
  3165. // @method getMaxZoom(): Number
  3166. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3167. getMaxZoom: function () {
  3168. return this.options.maxZoom === undefined ?
  3169. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3170. this.options.maxZoom;
  3171. },
  3172. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3173. // Returns the maximum zoom level on which the given bounds fit to the map
  3174. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3175. // instead returns the minimum zoom level on which the map view fits into
  3176. // the given bounds in its entirety.
  3177. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3178. bounds = toLatLngBounds(bounds);
  3179. padding = toPoint(padding || [0, 0]);
  3180. var zoom = this.getZoom() || 0,
  3181. min = this.getMinZoom(),
  3182. max = this.getMaxZoom(),
  3183. nw = bounds.getNorthWest(),
  3184. se = bounds.getSouthEast(),
  3185. size = this.getSize().subtract(padding),
  3186. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3187. snap = any3d ? this.options.zoomSnap : 1,
  3188. scalex = size.x / boundsSize.x,
  3189. scaley = size.y / boundsSize.y,
  3190. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3191. zoom = this.getScaleZoom(scale, zoom);
  3192. if (snap) {
  3193. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3194. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3195. }
  3196. return Math.max(min, Math.min(max, zoom));
  3197. },
  3198. // @method getSize(): Point
  3199. // Returns the current size of the map container (in pixels).
  3200. getSize: function () {
  3201. if (!this._size || this._sizeChanged) {
  3202. this._size = new Point(
  3203. this._container.clientWidth || 0,
  3204. this._container.clientHeight || 0);
  3205. this._sizeChanged = false;
  3206. }
  3207. return this._size.clone();
  3208. },
  3209. // @method getPixelBounds(): Bounds
  3210. // Returns the bounds of the current map view in projected pixel
  3211. // coordinates (sometimes useful in layer and overlay implementations).
  3212. getPixelBounds: function (center, zoom) {
  3213. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3214. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3215. },
  3216. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3217. // the map pane? "left point of the map layer" can be confusing, specially
  3218. // since there can be negative offsets.
  3219. // @method getPixelOrigin(): Point
  3220. // Returns the projected pixel coordinates of the top left point of
  3221. // the map layer (useful in custom layer and overlay implementations).
  3222. getPixelOrigin: function () {
  3223. this._checkIfLoaded();
  3224. return this._pixelOrigin;
  3225. },
  3226. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3227. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3228. // If `zoom` is omitted, the map's current zoom level is used.
  3229. getPixelWorldBounds: function (zoom) {
  3230. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3231. },
  3232. // @section Other Methods
  3233. // @method getPane(pane: String|HTMLElement): HTMLElement
  3234. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3235. getPane: function (pane) {
  3236. return typeof pane === 'string' ? this._panes[pane] : pane;
  3237. },
  3238. // @method getPanes(): Object
  3239. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3240. // the panes as values.
  3241. getPanes: function () {
  3242. return this._panes;
  3243. },
  3244. // @method getContainer: HTMLElement
  3245. // Returns the HTML element that contains the map.
  3246. getContainer: function () {
  3247. return this._container;
  3248. },
  3249. // @section Conversion Methods
  3250. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3251. // Returns the scale factor to be applied to a map transition from zoom level
  3252. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3253. getZoomScale: function (toZoom, fromZoom) {
  3254. // TODO replace with universal implementation after refactoring projections
  3255. var crs = this.options.crs;
  3256. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3257. return crs.scale(toZoom) / crs.scale(fromZoom);
  3258. },
  3259. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3260. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3261. // level and everything is scaled by a factor of `scale`. Inverse of
  3262. // [`getZoomScale`](#map-getZoomScale).
  3263. getScaleZoom: function (scale, fromZoom) {
  3264. var crs = this.options.crs;
  3265. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3266. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3267. return isNaN(zoom) ? Infinity : zoom;
  3268. },
  3269. // @method project(latlng: LatLng, zoom: Number): Point
  3270. // Projects a geographical coordinate `LatLng` according to the projection
  3271. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3272. // `Transformation`. The result is pixel coordinate relative to
  3273. // the CRS origin.
  3274. project: function (latlng, zoom) {
  3275. zoom = zoom === undefined ? this._zoom : zoom;
  3276. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3277. },
  3278. // @method unproject(point: Point, zoom: Number): LatLng
  3279. // Inverse of [`project`](#map-project).
  3280. unproject: function (point, zoom) {
  3281. zoom = zoom === undefined ? this._zoom : zoom;
  3282. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3283. },
  3284. // @method layerPointToLatLng(point: Point): LatLng
  3285. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3286. // returns the corresponding geographical coordinate (for the current zoom level).
  3287. layerPointToLatLng: function (point) {
  3288. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3289. return this.unproject(projectedPoint);
  3290. },
  3291. // @method latLngToLayerPoint(latlng: LatLng): Point
  3292. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3293. // relative to the [origin pixel](#map-getpixelorigin).
  3294. latLngToLayerPoint: function (latlng) {
  3295. var projectedPoint = this.project(toLatLng(latlng))._round();
  3296. return projectedPoint._subtract(this.getPixelOrigin());
  3297. },
  3298. // @method wrapLatLng(latlng: LatLng): LatLng
  3299. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3300. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3301. // CRS's bounds.
  3302. // By default this means longitude is wrapped around the dateline so its
  3303. // value is between -180 and +180 degrees.
  3304. wrapLatLng: function (latlng) {
  3305. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3306. },
  3307. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3308. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3309. // its center is within the CRS's bounds.
  3310. // By default this means the center longitude is wrapped around the dateline so its
  3311. // value is between -180 and +180 degrees, and the majority of the bounds
  3312. // overlaps the CRS's bounds.
  3313. wrapLatLngBounds: function (latlng) {
  3314. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3315. },
  3316. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3317. // Returns the distance between two geographical coordinates according to
  3318. // the map's CRS. By default this measures distance in meters.
  3319. distance: function (latlng1, latlng2) {
  3320. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3321. },
  3322. // @method containerPointToLayerPoint(point: Point): Point
  3323. // Given a pixel coordinate relative to the map container, returns the corresponding
  3324. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3325. containerPointToLayerPoint: function (point) { // (Point)
  3326. return toPoint(point).subtract(this._getMapPanePos());
  3327. },
  3328. // @method layerPointToContainerPoint(point: Point): Point
  3329. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3330. // returns the corresponding pixel coordinate relative to the map container.
  3331. layerPointToContainerPoint: function (point) { // (Point)
  3332. return toPoint(point).add(this._getMapPanePos());
  3333. },
  3334. // @method containerPointToLatLng(point: Point): LatLng
  3335. // Given a pixel coordinate relative to the map container, returns
  3336. // the corresponding geographical coordinate (for the current zoom level).
  3337. containerPointToLatLng: function (point) {
  3338. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3339. return this.layerPointToLatLng(layerPoint);
  3340. },
  3341. // @method latLngToContainerPoint(latlng: LatLng): Point
  3342. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3343. // relative to the map container.
  3344. latLngToContainerPoint: function (latlng) {
  3345. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3346. },
  3347. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3348. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3349. // map container where the event took place.
  3350. mouseEventToContainerPoint: function (e) {
  3351. return getMousePosition(e, this._container);
  3352. },
  3353. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3354. // Given a MouseEvent object, returns the pixel coordinate relative to
  3355. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3356. mouseEventToLayerPoint: function (e) {
  3357. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3358. },
  3359. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3360. // Given a MouseEvent object, returns geographical coordinate where the
  3361. // event took place.
  3362. mouseEventToLatLng: function (e) { // (MouseEvent)
  3363. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3364. },
  3365. // map initialization methods
  3366. _initContainer: function (id) {
  3367. var container = this._container = get(id);
  3368. if (!container) {
  3369. throw new Error('Map container not found.');
  3370. } else if (container._leaflet_id) {
  3371. throw new Error('Map container is already initialized.');
  3372. }
  3373. on(container, 'scroll', this._onScroll, this);
  3374. this._containerId = stamp(container);
  3375. },
  3376. _initLayout: function () {
  3377. var container = this._container;
  3378. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3379. addClass(container, 'leaflet-container' +
  3380. (touch ? ' leaflet-touch' : '') +
  3381. (retina ? ' leaflet-retina' : '') +
  3382. (ielt9 ? ' leaflet-oldie' : '') +
  3383. (safari ? ' leaflet-safari' : '') +
  3384. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3385. var position = getStyle(container, 'position');
  3386. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3387. container.style.position = 'relative';
  3388. }
  3389. this._initPanes();
  3390. if (this._initControlPos) {
  3391. this._initControlPos();
  3392. }
  3393. },
  3394. _initPanes: function () {
  3395. var panes = this._panes = {};
  3396. this._paneRenderers = {};
  3397. // @section
  3398. //
  3399. // Panes are DOM elements used to control the ordering of layers on the map. You
  3400. // can access panes with [`map.getPane`](#map-getpane) or
  3401. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3402. // [`map.createPane`](#map-createpane) method.
  3403. //
  3404. // Every map has the following default panes that differ only in zIndex.
  3405. //
  3406. // @pane mapPane: HTMLElement = 'auto'
  3407. // Pane that contains all other map panes
  3408. this._mapPane = this.createPane('mapPane', this._container);
  3409. setPosition(this._mapPane, new Point(0, 0));
  3410. // @pane tilePane: HTMLElement = 200
  3411. // Pane for `GridLayer`s and `TileLayer`s
  3412. this.createPane('tilePane');
  3413. // @pane overlayPane: HTMLElement = 400
  3414. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3415. this.createPane('shadowPane');
  3416. // @pane shadowPane: HTMLElement = 500
  3417. // Pane for overlay shadows (e.g. `Marker` shadows)
  3418. this.createPane('overlayPane');
  3419. // @pane markerPane: HTMLElement = 600
  3420. // Pane for `Icon`s of `Marker`s
  3421. this.createPane('markerPane');
  3422. // @pane tooltipPane: HTMLElement = 650
  3423. // Pane for `Tooltip`s.
  3424. this.createPane('tooltipPane');
  3425. // @pane popupPane: HTMLElement = 700
  3426. // Pane for `Popup`s.
  3427. this.createPane('popupPane');
  3428. if (!this.options.markerZoomAnimation) {
  3429. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3430. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3431. }
  3432. },
  3433. // private methods that modify map state
  3434. // @section Map state change events
  3435. _resetView: function (center, zoom) {
  3436. setPosition(this._mapPane, new Point(0, 0));
  3437. var loading = !this._loaded;
  3438. this._loaded = true;
  3439. zoom = this._limitZoom(zoom);
  3440. this.fire('viewprereset');
  3441. var zoomChanged = this._zoom !== zoom;
  3442. this
  3443. ._moveStart(zoomChanged, false)
  3444. ._move(center, zoom)
  3445. ._moveEnd(zoomChanged);
  3446. // @event viewreset: Event
  3447. // Fired when the map needs to redraw its content (this usually happens
  3448. // on map zoom or load). Very useful for creating custom overlays.
  3449. this.fire('viewreset');
  3450. // @event load: Event
  3451. // Fired when the map is initialized (when its center and zoom are set
  3452. // for the first time).
  3453. if (loading) {
  3454. this.fire('load');
  3455. }
  3456. },
  3457. _moveStart: function (zoomChanged, noMoveStart) {
  3458. // @event zoomstart: Event
  3459. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3460. // @event movestart: Event
  3461. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3462. if (zoomChanged) {
  3463. this.fire('zoomstart');
  3464. }
  3465. if (!noMoveStart) {
  3466. this.fire('movestart');
  3467. }
  3468. return this;
  3469. },
  3470. _move: function (center, zoom, data) {
  3471. if (zoom === undefined) {
  3472. zoom = this._zoom;
  3473. }
  3474. var zoomChanged = this._zoom !== zoom;
  3475. this._zoom = zoom;
  3476. this._lastCenter = center;
  3477. this._pixelOrigin = this._getNewPixelOrigin(center);
  3478. // @event zoom: Event
  3479. // Fired repeatedly during any change in zoom level, including zoom
  3480. // and fly animations.
  3481. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3482. this.fire('zoom', data);
  3483. }
  3484. // @event move: Event
  3485. // Fired repeatedly during any movement of the map, including pan and
  3486. // fly animations.
  3487. return this.fire('move', data);
  3488. },
  3489. _moveEnd: function (zoomChanged) {
  3490. // @event zoomend: Event
  3491. // Fired when the map has changed, after any animations.
  3492. if (zoomChanged) {
  3493. this.fire('zoomend');
  3494. }
  3495. // @event moveend: Event
  3496. // Fired when the center of the map stops changing (e.g. user stopped
  3497. // dragging the map).
  3498. return this.fire('moveend');
  3499. },
  3500. _stop: function () {
  3501. cancelAnimFrame(this._flyToFrame);
  3502. if (this._panAnim) {
  3503. this._panAnim.stop();
  3504. }
  3505. return this;
  3506. },
  3507. _rawPanBy: function (offset) {
  3508. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3509. },
  3510. _getZoomSpan: function () {
  3511. return this.getMaxZoom() - this.getMinZoom();
  3512. },
  3513. _panInsideMaxBounds: function () {
  3514. if (!this._enforcingBounds) {
  3515. this.panInsideBounds(this.options.maxBounds);
  3516. }
  3517. },
  3518. _checkIfLoaded: function () {
  3519. if (!this._loaded) {
  3520. throw new Error('Set map center and zoom first.');
  3521. }
  3522. },
  3523. // DOM event handling
  3524. // @section Interaction events
  3525. _initEvents: function (remove$$1) {
  3526. this._targets = {};
  3527. this._targets[stamp(this._container)] = this;
  3528. var onOff = remove$$1 ? off : on;
  3529. // @event click: MouseEvent
  3530. // Fired when the user clicks (or taps) the map.
  3531. // @event dblclick: MouseEvent
  3532. // Fired when the user double-clicks (or double-taps) the map.
  3533. // @event mousedown: MouseEvent
  3534. // Fired when the user pushes the mouse button on the map.
  3535. // @event mouseup: MouseEvent
  3536. // Fired when the user releases the mouse button on the map.
  3537. // @event mouseover: MouseEvent
  3538. // Fired when the mouse enters the map.
  3539. // @event mouseout: MouseEvent
  3540. // Fired when the mouse leaves the map.
  3541. // @event mousemove: MouseEvent
  3542. // Fired while the mouse moves over the map.
  3543. // @event contextmenu: MouseEvent
  3544. // Fired when the user pushes the right mouse button on the map, prevents
  3545. // default browser context menu from showing if there are listeners on
  3546. // this event. Also fired on mobile when the user holds a single touch
  3547. // for a second (also called long press).
  3548. // @event keypress: KeyboardEvent
  3549. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3550. // @event keydown: KeyboardEvent
  3551. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3552. // the `keydown` event is fired for keys that produce a character value and for keys
  3553. // that do not produce a character value.
  3554. // @event keyup: KeyboardEvent
  3555. // Fired when the user releases a key from the keyboard while the map is focused.
  3556. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3557. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3558. if (this.options.trackResize) {
  3559. onOff(window, 'resize', this._onResize, this);
  3560. }
  3561. if (any3d && this.options.transform3DLimit) {
  3562. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3563. }
  3564. },
  3565. _onResize: function () {
  3566. cancelAnimFrame(this._resizeRequest);
  3567. this._resizeRequest = requestAnimFrame(
  3568. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3569. },
  3570. _onScroll: function () {
  3571. this._container.scrollTop = 0;
  3572. this._container.scrollLeft = 0;
  3573. },
  3574. _onMoveEnd: function () {
  3575. var pos = this._getMapPanePos();
  3576. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3577. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3578. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3579. this._resetView(this.getCenter(), this.getZoom());
  3580. }
  3581. },
  3582. _findEventTargets: function (e, type) {
  3583. var targets = [],
  3584. target,
  3585. isHover = type === 'mouseout' || type === 'mouseover',
  3586. src = e.target || e.srcElement,
  3587. dragging = false;
  3588. while (src) {
  3589. target = this._targets[stamp(src)];
  3590. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3591. // Prevent firing click after you just dragged an object.
  3592. dragging = true;
  3593. break;
  3594. }
  3595. if (target && target.listens(type, true)) {
  3596. if (isHover && !isExternalTarget(src, e)) { break; }
  3597. targets.push(target);
  3598. if (isHover) { break; }
  3599. }
  3600. if (src === this._container) { break; }
  3601. src = src.parentNode;
  3602. }
  3603. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3604. targets = [this];
  3605. }
  3606. return targets;
  3607. },
  3608. _handleDOMEvent: function (e) {
  3609. if (!this._loaded || skipped(e)) { return; }
  3610. var type = e.type;
  3611. if (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') {
  3612. // prevents outline when clicking on keyboard-focusable element
  3613. preventOutline(e.target || e.srcElement);
  3614. }
  3615. this._fireDOMEvent(e, type);
  3616. },
  3617. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3618. _fireDOMEvent: function (e, type, targets) {
  3619. if (e.type === 'click') {
  3620. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3621. // @event preclick: MouseEvent
  3622. // Fired before mouse click on the map (sometimes useful when you
  3623. // want something to happen on click before any existing click
  3624. // handlers start running).
  3625. var synth = extend({}, e);
  3626. synth.type = 'preclick';
  3627. this._fireDOMEvent(synth, synth.type, targets);
  3628. }
  3629. if (e._stopped) { return; }
  3630. // Find the layer the event is propagating from and its parents.
  3631. targets = (targets || []).concat(this._findEventTargets(e, type));
  3632. if (!targets.length) { return; }
  3633. var target = targets[0];
  3634. if (type === 'contextmenu' && target.listens(type, true)) {
  3635. preventDefault(e);
  3636. }
  3637. var data = {
  3638. originalEvent: e
  3639. };
  3640. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3641. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3642. data.containerPoint = isMarker ?
  3643. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3644. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3645. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3646. }
  3647. for (var i = 0; i < targets.length; i++) {
  3648. targets[i].fire(type, data, true);
  3649. if (data.originalEvent._stopped ||
  3650. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3651. }
  3652. },
  3653. _draggableMoved: function (obj) {
  3654. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3655. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3656. },
  3657. _clearHandlers: function () {
  3658. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3659. this._handlers[i].disable();
  3660. }
  3661. },
  3662. // @section Other Methods
  3663. // @method whenReady(fn: Function, context?: Object): this
  3664. // Runs the given function `fn` when the map gets initialized with
  3665. // a view (center and zoom) and at least one layer, or immediately
  3666. // if it's already initialized, optionally passing a function context.
  3667. whenReady: function (callback, context) {
  3668. if (this._loaded) {
  3669. callback.call(context || this, {target: this});
  3670. } else {
  3671. this.on('load', callback, context);
  3672. }
  3673. return this;
  3674. },
  3675. // private methods for getting map state
  3676. _getMapPanePos: function () {
  3677. return getPosition(this._mapPane) || new Point(0, 0);
  3678. },
  3679. _moved: function () {
  3680. var pos = this._getMapPanePos();
  3681. return pos && !pos.equals([0, 0]);
  3682. },
  3683. _getTopLeftPoint: function (center, zoom) {
  3684. var pixelOrigin = center && zoom !== undefined ?
  3685. this._getNewPixelOrigin(center, zoom) :
  3686. this.getPixelOrigin();
  3687. return pixelOrigin.subtract(this._getMapPanePos());
  3688. },
  3689. _getNewPixelOrigin: function (center, zoom) {
  3690. var viewHalf = this.getSize()._divideBy(2);
  3691. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3692. },
  3693. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3694. var topLeft = this._getNewPixelOrigin(center, zoom);
  3695. return this.project(latlng, zoom)._subtract(topLeft);
  3696. },
  3697. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3698. var topLeft = this._getNewPixelOrigin(center, zoom);
  3699. return toBounds([
  3700. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3701. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3702. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3703. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3704. ]);
  3705. },
  3706. // layer point of the current center
  3707. _getCenterLayerPoint: function () {
  3708. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3709. },
  3710. // offset of the specified place to the current center in pixels
  3711. _getCenterOffset: function (latlng) {
  3712. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3713. },
  3714. // adjust center for view to get inside bounds
  3715. _limitCenter: function (center, zoom, bounds) {
  3716. if (!bounds) { return center; }
  3717. var centerPoint = this.project(center, zoom),
  3718. viewHalf = this.getSize().divideBy(2),
  3719. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3720. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3721. // If offset is less than a pixel, ignore.
  3722. // This prevents unstable projections from getting into
  3723. // an infinite loop of tiny offsets.
  3724. if (offset.round().equals([0, 0])) {
  3725. return center;
  3726. }
  3727. return this.unproject(centerPoint.add(offset), zoom);
  3728. },
  3729. // adjust offset for view to get inside bounds
  3730. _limitOffset: function (offset, bounds) {
  3731. if (!bounds) { return offset; }
  3732. var viewBounds = this.getPixelBounds(),
  3733. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3734. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3735. },
  3736. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3737. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3738. var projectedMaxBounds = toBounds(
  3739. this.project(maxBounds.getNorthEast(), zoom),
  3740. this.project(maxBounds.getSouthWest(), zoom)
  3741. ),
  3742. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3743. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3744. dx = this._rebound(minOffset.x, -maxOffset.x),
  3745. dy = this._rebound(minOffset.y, -maxOffset.y);
  3746. return new Point(dx, dy);
  3747. },
  3748. _rebound: function (left, right) {
  3749. return left + right > 0 ?
  3750. Math.round(left - right) / 2 :
  3751. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3752. },
  3753. _limitZoom: function (zoom) {
  3754. var min = this.getMinZoom(),
  3755. max = this.getMaxZoom(),
  3756. snap = any3d ? this.options.zoomSnap : 1;
  3757. if (snap) {
  3758. zoom = Math.round(zoom / snap) * snap;
  3759. }
  3760. return Math.max(min, Math.min(max, zoom));
  3761. },
  3762. _onPanTransitionStep: function () {
  3763. this.fire('move');
  3764. },
  3765. _onPanTransitionEnd: function () {
  3766. removeClass(this._mapPane, 'leaflet-pan-anim');
  3767. this.fire('moveend');
  3768. },
  3769. _tryAnimatedPan: function (center, options) {
  3770. // difference between the new and current centers in pixels
  3771. var offset = this._getCenterOffset(center)._trunc();
  3772. // don't animate too far unless animate: true specified in options
  3773. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3774. this.panBy(offset, options);
  3775. return true;
  3776. },
  3777. _createAnimProxy: function () {
  3778. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3779. this._panes.mapPane.appendChild(proxy);
  3780. this.on('zoomanim', function (e) {
  3781. var prop = TRANSFORM,
  3782. transform = this._proxy.style[prop];
  3783. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3784. // workaround for case when transform is the same and so transitionend event is not fired
  3785. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3786. this._onZoomTransitionEnd();
  3787. }
  3788. }, this);
  3789. this.on('load moveend', function () {
  3790. var c = this.getCenter(),
  3791. z = this.getZoom();
  3792. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3793. }, this);
  3794. this._on('unload', this._destroyAnimProxy, this);
  3795. },
  3796. _destroyAnimProxy: function () {
  3797. remove(this._proxy);
  3798. delete this._proxy;
  3799. },
  3800. _catchTransitionEnd: function (e) {
  3801. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3802. this._onZoomTransitionEnd();
  3803. }
  3804. },
  3805. _nothingToAnimate: function () {
  3806. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3807. },
  3808. _tryAnimatedZoom: function (center, zoom, options) {
  3809. if (this._animatingZoom) { return true; }
  3810. options = options || {};
  3811. // don't animate if disabled, not supported or zoom difference is too large
  3812. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3813. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3814. // offset is the pixel coords of the zoom origin relative to the current center
  3815. var scale = this.getZoomScale(zoom),
  3816. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3817. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3818. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3819. requestAnimFrame(function () {
  3820. this
  3821. ._moveStart(true, false)
  3822. ._animateZoom(center, zoom, true);
  3823. }, this);
  3824. return true;
  3825. },
  3826. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3827. if (!this._mapPane) { return; }
  3828. if (startAnim) {
  3829. this._animatingZoom = true;
  3830. // remember what center/zoom to set after animation
  3831. this._animateToCenter = center;
  3832. this._animateToZoom = zoom;
  3833. addClass(this._mapPane, 'leaflet-zoom-anim');
  3834. }
  3835. // @event zoomanim: ZoomAnimEvent
  3836. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3837. this.fire('zoomanim', {
  3838. center: center,
  3839. zoom: zoom,
  3840. noUpdate: noUpdate
  3841. });
  3842. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3843. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3844. },
  3845. _onZoomTransitionEnd: function () {
  3846. if (!this._animatingZoom) { return; }
  3847. if (this._mapPane) {
  3848. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3849. }
  3850. this._animatingZoom = false;
  3851. this._move(this._animateToCenter, this._animateToZoom);
  3852. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3853. requestAnimFrame(function () {
  3854. this._moveEnd(true);
  3855. }, this);
  3856. }
  3857. });
  3858. // @section
  3859. // @factory L.map(id: String, options?: Map options)
  3860. // Instantiates a map object given the DOM ID of a `<div>` element
  3861. // and optionally an object literal with `Map options`.
  3862. //
  3863. // @alternative
  3864. // @factory L.map(el: HTMLElement, options?: Map options)
  3865. // Instantiates a map object given an instance of a `<div>` HTML element
  3866. // and optionally an object literal with `Map options`.
  3867. function createMap(id, options) {
  3868. return new Map(id, options);
  3869. }
  3870. /*
  3871. * @class Control
  3872. * @aka L.Control
  3873. * @inherits Class
  3874. *
  3875. * L.Control is a base class for implementing map controls. Handles positioning.
  3876. * All other controls extend from this class.
  3877. */
  3878. var Control = Class.extend({
  3879. // @section
  3880. // @aka Control options
  3881. options: {
  3882. // @option position: String = 'topright'
  3883. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3884. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3885. position: 'topright'
  3886. },
  3887. initialize: function (options) {
  3888. setOptions(this, options);
  3889. },
  3890. /* @section
  3891. * Classes extending L.Control will inherit the following methods:
  3892. *
  3893. * @method getPosition: string
  3894. * Returns the position of the control.
  3895. */
  3896. getPosition: function () {
  3897. return this.options.position;
  3898. },
  3899. // @method setPosition(position: string): this
  3900. // Sets the position of the control.
  3901. setPosition: function (position) {
  3902. var map = this._map;
  3903. if (map) {
  3904. map.removeControl(this);
  3905. }
  3906. this.options.position = position;
  3907. if (map) {
  3908. map.addControl(this);
  3909. }
  3910. return this;
  3911. },
  3912. // @method getContainer: HTMLElement
  3913. // Returns the HTMLElement that contains the control.
  3914. getContainer: function () {
  3915. return this._container;
  3916. },
  3917. // @method addTo(map: Map): this
  3918. // Adds the control to the given map.
  3919. addTo: function (map) {
  3920. this.remove();
  3921. this._map = map;
  3922. var container = this._container = this.onAdd(map),
  3923. pos = this.getPosition(),
  3924. corner = map._controlCorners[pos];
  3925. addClass(container, 'leaflet-control');
  3926. if (pos.indexOf('bottom') !== -1) {
  3927. corner.insertBefore(container, corner.firstChild);
  3928. } else {
  3929. corner.appendChild(container);
  3930. }
  3931. this._map.on('unload', this.remove, this);
  3932. return this;
  3933. },
  3934. // @method remove: this
  3935. // Removes the control from the map it is currently active on.
  3936. remove: function () {
  3937. if (!this._map) {
  3938. return this;
  3939. }
  3940. remove(this._container);
  3941. if (this.onRemove) {
  3942. this.onRemove(this._map);
  3943. }
  3944. this._map.off('unload', this.remove, this);
  3945. this._map = null;
  3946. return this;
  3947. },
  3948. _refocusOnMap: function (e) {
  3949. // if map exists and event is not a keyboard event
  3950. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3951. this._map.getContainer().focus();
  3952. }
  3953. }
  3954. });
  3955. var control = function (options) {
  3956. return new Control(options);
  3957. };
  3958. /* @section Extension methods
  3959. * @uninheritable
  3960. *
  3961. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3962. *
  3963. * @method onAdd(map: Map): HTMLElement
  3964. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3965. *
  3966. * @method onRemove(map: Map)
  3967. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3968. */
  3969. /* @namespace Map
  3970. * @section Methods for Layers and Controls
  3971. */
  3972. Map.include({
  3973. // @method addControl(control: Control): this
  3974. // Adds the given control to the map
  3975. addControl: function (control) {
  3976. control.addTo(this);
  3977. return this;
  3978. },
  3979. // @method removeControl(control: Control): this
  3980. // Removes the given control from the map
  3981. removeControl: function (control) {
  3982. control.remove();
  3983. return this;
  3984. },
  3985. _initControlPos: function () {
  3986. var corners = this._controlCorners = {},
  3987. l = 'leaflet-',
  3988. container = this._controlContainer =
  3989. create$1('div', l + 'control-container', this._container);
  3990. function createCorner(vSide, hSide) {
  3991. var className = l + vSide + ' ' + l + hSide;
  3992. corners[vSide + hSide] = create$1('div', className, container);
  3993. }
  3994. createCorner('top', 'left');
  3995. createCorner('top', 'right');
  3996. createCorner('bottom', 'left');
  3997. createCorner('bottom', 'right');
  3998. },
  3999. _clearControlPos: function () {
  4000. for (var i in this._controlCorners) {
  4001. remove(this._controlCorners[i]);
  4002. }
  4003. remove(this._controlContainer);
  4004. delete this._controlCorners;
  4005. delete this._controlContainer;
  4006. }
  4007. });
  4008. /*
  4009. * @class Control.Layers
  4010. * @aka L.Control.Layers
  4011. * @inherits Control
  4012. *
  4013. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`.
  4014. *
  4015. * @example
  4016. *
  4017. * ```js
  4018. * var baseLayers = {
  4019. * "Mapbox": mapbox,
  4020. * "OpenStreetMap": osm
  4021. * };
  4022. *
  4023. * var overlays = {
  4024. * "Marker": marker,
  4025. * "Roads": roadsLayer
  4026. * };
  4027. *
  4028. * L.control.layers(baseLayers, overlays).addTo(map);
  4029. * ```
  4030. *
  4031. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4032. *
  4033. * ```js
  4034. * {
  4035. * "<someName1>": layer1,
  4036. * "<someName2>": layer2
  4037. * }
  4038. * ```
  4039. *
  4040. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4041. *
  4042. * ```js
  4043. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4044. * ```
  4045. */
  4046. var Layers = Control.extend({
  4047. // @section
  4048. // @aka Control.Layers options
  4049. options: {
  4050. // @option collapsed: Boolean = true
  4051. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  4052. collapsed: true,
  4053. position: 'topright',
  4054. // @option autoZIndex: Boolean = true
  4055. // If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
  4056. autoZIndex: true,
  4057. // @option hideSingleBase: Boolean = false
  4058. // If `true`, the base layers in the control will be hidden when there is only one.
  4059. hideSingleBase: false,
  4060. // @option sortLayers: Boolean = false
  4061. // Whether to sort the layers. When `false`, layers will keep the order
  4062. // in which they were added to the control.
  4063. sortLayers: false,
  4064. // @option sortFunction: Function = *
  4065. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4066. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4067. // The function receives both the `L.Layer` instances and their names, as in
  4068. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4069. // By default, it sorts layers alphabetically by their name.
  4070. sortFunction: function (layerA, layerB, nameA, nameB) {
  4071. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4072. }
  4073. },
  4074. initialize: function (baseLayers, overlays, options) {
  4075. setOptions(this, options);
  4076. this._layerControlInputs = [];
  4077. this._layers = [];
  4078. this._lastZIndex = 0;
  4079. this._handlingClick = false;
  4080. for (var i in baseLayers) {
  4081. this._addLayer(baseLayers[i], i);
  4082. }
  4083. for (i in overlays) {
  4084. this._addLayer(overlays[i], i, true);
  4085. }
  4086. },
  4087. onAdd: function (map) {
  4088. this._initLayout();
  4089. this._update();
  4090. this._map = map;
  4091. map.on('zoomend', this._checkDisabledLayers, this);
  4092. for (var i = 0; i < this._layers.length; i++) {
  4093. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4094. }
  4095. return this._container;
  4096. },
  4097. addTo: function (map) {
  4098. Control.prototype.addTo.call(this, map);
  4099. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4100. return this._expandIfNotCollapsed();
  4101. },
  4102. onRemove: function () {
  4103. this._map.off('zoomend', this._checkDisabledLayers, this);
  4104. for (var i = 0; i < this._layers.length; i++) {
  4105. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4106. }
  4107. },
  4108. // @method addBaseLayer(layer: Layer, name: String): this
  4109. // Adds a base layer (radio button entry) with the given name to the control.
  4110. addBaseLayer: function (layer, name) {
  4111. this._addLayer(layer, name);
  4112. return (this._map) ? this._update() : this;
  4113. },
  4114. // @method addOverlay(layer: Layer, name: String): this
  4115. // Adds an overlay (checkbox entry) with the given name to the control.
  4116. addOverlay: function (layer, name) {
  4117. this._addLayer(layer, name, true);
  4118. return (this._map) ? this._update() : this;
  4119. },
  4120. // @method removeLayer(layer: Layer): this
  4121. // Remove the given layer from the control.
  4122. removeLayer: function (layer) {
  4123. layer.off('add remove', this._onLayerChange, this);
  4124. var obj = this._getLayer(stamp(layer));
  4125. if (obj) {
  4126. this._layers.splice(this._layers.indexOf(obj), 1);
  4127. }
  4128. return (this._map) ? this._update() : this;
  4129. },
  4130. // @method expand(): this
  4131. // Expand the control container if collapsed.
  4132. expand: function () {
  4133. addClass(this._container, 'leaflet-control-layers-expanded');
  4134. this._section.style.height = null;
  4135. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4136. if (acceptableHeight < this._section.clientHeight) {
  4137. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4138. this._section.style.height = acceptableHeight + 'px';
  4139. } else {
  4140. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4141. }
  4142. this._checkDisabledLayers();
  4143. return this;
  4144. },
  4145. // @method collapse(): this
  4146. // Collapse the control container if expanded.
  4147. collapse: function () {
  4148. removeClass(this._container, 'leaflet-control-layers-expanded');
  4149. return this;
  4150. },
  4151. _initLayout: function () {
  4152. var className = 'leaflet-control-layers',
  4153. container = this._container = create$1('div', className),
  4154. collapsed = this.options.collapsed;
  4155. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4156. container.setAttribute('aria-haspopup', true);
  4157. disableClickPropagation(container);
  4158. disableScrollPropagation(container);
  4159. var section = this._section = create$1('section', className + '-list');
  4160. if (collapsed) {
  4161. this._map.on('click', this.collapse, this);
  4162. if (!android) {
  4163. on(container, {
  4164. mouseenter: this.expand,
  4165. mouseleave: this.collapse
  4166. }, this);
  4167. }
  4168. }
  4169. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4170. link.href = '#';
  4171. link.title = 'Layers';
  4172. if (touch) {
  4173. on(link, 'click', stop);
  4174. on(link, 'click', this.expand, this);
  4175. } else {
  4176. on(link, 'focus', this.expand, this);
  4177. }
  4178. if (!collapsed) {
  4179. this.expand();
  4180. }
  4181. this._baseLayersList = create$1('div', className + '-base', section);
  4182. this._separator = create$1('div', className + '-separator', section);
  4183. this._overlaysList = create$1('div', className + '-overlays', section);
  4184. container.appendChild(section);
  4185. },
  4186. _getLayer: function (id) {
  4187. for (var i = 0; i < this._layers.length; i++) {
  4188. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4189. return this._layers[i];
  4190. }
  4191. }
  4192. },
  4193. _addLayer: function (layer, name, overlay) {
  4194. if (this._map) {
  4195. layer.on('add remove', this._onLayerChange, this);
  4196. }
  4197. this._layers.push({
  4198. layer: layer,
  4199. name: name,
  4200. overlay: overlay
  4201. });
  4202. if (this.options.sortLayers) {
  4203. this._layers.sort(bind(function (a, b) {
  4204. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4205. }, this));
  4206. }
  4207. if (this.options.autoZIndex && layer.setZIndex) {
  4208. this._lastZIndex++;
  4209. layer.setZIndex(this._lastZIndex);
  4210. }
  4211. this._expandIfNotCollapsed();
  4212. },
  4213. _update: function () {
  4214. if (!this._container) { return this; }
  4215. empty(this._baseLayersList);
  4216. empty(this._overlaysList);
  4217. this._layerControlInputs = [];
  4218. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4219. for (i = 0; i < this._layers.length; i++) {
  4220. obj = this._layers[i];
  4221. this._addItem(obj);
  4222. overlaysPresent = overlaysPresent || obj.overlay;
  4223. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4224. baseLayersCount += !obj.overlay ? 1 : 0;
  4225. }
  4226. // Hide base layers section if there's only one layer.
  4227. if (this.options.hideSingleBase) {
  4228. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4229. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4230. }
  4231. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4232. return this;
  4233. },
  4234. _onLayerChange: function (e) {
  4235. if (!this._handlingClick) {
  4236. this._update();
  4237. }
  4238. var obj = this._getLayer(stamp(e.target));
  4239. // @namespace Map
  4240. // @section Layer events
  4241. // @event baselayerchange: LayersControlEvent
  4242. // Fired when the base layer is changed through the [layer control](#control-layers).
  4243. // @event overlayadd: LayersControlEvent
  4244. // Fired when an overlay is selected through the [layer control](#control-layers).
  4245. // @event overlayremove: LayersControlEvent
  4246. // Fired when an overlay is deselected through the [layer control](#control-layers).
  4247. // @namespace Control.Layers
  4248. var type = obj.overlay ?
  4249. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4250. (e.type === 'add' ? 'baselayerchange' : null);
  4251. if (type) {
  4252. this._map.fire(type, obj);
  4253. }
  4254. },
  4255. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4256. _createRadioElement: function (name, checked) {
  4257. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4258. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4259. var radioFragment = document.createElement('div');
  4260. radioFragment.innerHTML = radioHtml;
  4261. return radioFragment.firstChild;
  4262. },
  4263. _addItem: function (obj) {
  4264. var label = document.createElement('label'),
  4265. checked = this._map.hasLayer(obj.layer),
  4266. input;
  4267. if (obj.overlay) {
  4268. input = document.createElement('input');
  4269. input.type = 'checkbox';
  4270. input.className = 'leaflet-control-layers-selector';
  4271. input.defaultChecked = checked;
  4272. } else {
  4273. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4274. }
  4275. this._layerControlInputs.push(input);
  4276. input.layerId = stamp(obj.layer);
  4277. on(input, 'click', this._onInputClick, this);
  4278. var name = document.createElement('span');
  4279. name.innerHTML = ' ' + obj.name;
  4280. // Helps from preventing layer control flicker when checkboxes are disabled
  4281. // https://github.com/Leaflet/Leaflet/issues/2771
  4282. var holder = document.createElement('div');
  4283. label.appendChild(holder);
  4284. holder.appendChild(input);
  4285. holder.appendChild(name);
  4286. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4287. container.appendChild(label);
  4288. this._checkDisabledLayers();
  4289. return label;
  4290. },
  4291. _onInputClick: function () {
  4292. var inputs = this._layerControlInputs,
  4293. input, layer;
  4294. var addedLayers = [],
  4295. removedLayers = [];
  4296. this._handlingClick = true;
  4297. for (var i = inputs.length - 1; i >= 0; i--) {
  4298. input = inputs[i];
  4299. layer = this._getLayer(input.layerId).layer;
  4300. if (input.checked) {
  4301. addedLayers.push(layer);
  4302. } else if (!input.checked) {
  4303. removedLayers.push(layer);
  4304. }
  4305. }
  4306. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4307. for (i = 0; i < removedLayers.length; i++) {
  4308. if (this._map.hasLayer(removedLayers[i])) {
  4309. this._map.removeLayer(removedLayers[i]);
  4310. }
  4311. }
  4312. for (i = 0; i < addedLayers.length; i++) {
  4313. if (!this._map.hasLayer(addedLayers[i])) {
  4314. this._map.addLayer(addedLayers[i]);
  4315. }
  4316. }
  4317. this._handlingClick = false;
  4318. this._refocusOnMap();
  4319. },
  4320. _checkDisabledLayers: function () {
  4321. var inputs = this._layerControlInputs,
  4322. input,
  4323. layer,
  4324. zoom = this._map.getZoom();
  4325. for (var i = inputs.length - 1; i >= 0; i--) {
  4326. input = inputs[i];
  4327. layer = this._getLayer(input.layerId).layer;
  4328. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4329. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4330. }
  4331. },
  4332. _expandIfNotCollapsed: function () {
  4333. if (this._map && !this.options.collapsed) {
  4334. this.expand();
  4335. }
  4336. return this;
  4337. },
  4338. _expand: function () {
  4339. // Backward compatibility, remove me in 1.1.
  4340. return this.expand();
  4341. },
  4342. _collapse: function () {
  4343. // Backward compatibility, remove me in 1.1.
  4344. return this.collapse();
  4345. }
  4346. });
  4347. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4348. // Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
  4349. var layers = function (baseLayers, overlays, options) {
  4350. return new Layers(baseLayers, overlays, options);
  4351. };
  4352. /*
  4353. * @class Control.Zoom
  4354. * @aka L.Control.Zoom
  4355. * @inherits Control
  4356. *
  4357. * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.
  4358. */
  4359. var Zoom = Control.extend({
  4360. // @section
  4361. // @aka Control.Zoom options
  4362. options: {
  4363. position: 'topleft',
  4364. // @option zoomInText: String = '+'
  4365. // The text set on the 'zoom in' button.
  4366. zoomInText: '+',
  4367. // @option zoomInTitle: String = 'Zoom in'
  4368. // The title set on the 'zoom in' button.
  4369. zoomInTitle: 'Zoom in',
  4370. // @option zoomOutText: String = '&#x2212;'
  4371. // The text set on the 'zoom out' button.
  4372. zoomOutText: '&#x2212;',
  4373. // @option zoomOutTitle: String = 'Zoom out'
  4374. // The title set on the 'zoom out' button.
  4375. zoomOutTitle: 'Zoom out'
  4376. },
  4377. onAdd: function (map) {
  4378. var zoomName = 'leaflet-control-zoom',
  4379. container = create$1('div', zoomName + ' leaflet-bar'),
  4380. options = this.options;
  4381. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4382. zoomName + '-in', container, this._zoomIn);
  4383. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4384. zoomName + '-out', container, this._zoomOut);
  4385. this._updateDisabled();
  4386. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4387. return container;
  4388. },
  4389. onRemove: function (map) {
  4390. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4391. },
  4392. disable: function () {
  4393. this._disabled = true;
  4394. this._updateDisabled();
  4395. return this;
  4396. },
  4397. enable: function () {
  4398. this._disabled = false;
  4399. this._updateDisabled();
  4400. return this;
  4401. },
  4402. _zoomIn: function (e) {
  4403. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4404. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4405. }
  4406. },
  4407. _zoomOut: function (e) {
  4408. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4409. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4410. }
  4411. },
  4412. _createButton: function (html, title, className, container, fn) {
  4413. var link = create$1('a', className, container);
  4414. link.innerHTML = html;
  4415. link.href = '#';
  4416. link.title = title;
  4417. /*
  4418. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4419. */
  4420. link.setAttribute('role', 'button');
  4421. link.setAttribute('aria-label', title);
  4422. disableClickPropagation(link);
  4423. on(link, 'click', stop);
  4424. on(link, 'click', fn, this);
  4425. on(link, 'click', this._refocusOnMap, this);
  4426. return link;
  4427. },
  4428. _updateDisabled: function () {
  4429. var map = this._map,
  4430. className = 'leaflet-disabled';
  4431. removeClass(this._zoomInButton, className);
  4432. removeClass(this._zoomOutButton, className);
  4433. if (this._disabled || map._zoom === map.getMinZoom()) {
  4434. addClass(this._zoomOutButton, className);
  4435. }
  4436. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4437. addClass(this._zoomInButton, className);
  4438. }
  4439. }
  4440. });
  4441. // @namespace Map
  4442. // @section Control options
  4443. // @option zoomControl: Boolean = true
  4444. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4445. Map.mergeOptions({
  4446. zoomControl: true
  4447. });
  4448. Map.addInitHook(function () {
  4449. if (this.options.zoomControl) {
  4450. // @section Controls
  4451. // @property zoomControl: Control.Zoom
  4452. // The default zoom control (only available if the
  4453. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4454. this.zoomControl = new Zoom();
  4455. this.addControl(this.zoomControl);
  4456. }
  4457. });
  4458. // @namespace Control.Zoom
  4459. // @factory L.control.zoom(options: Control.Zoom options)
  4460. // Creates a zoom control
  4461. var zoom = function (options) {
  4462. return new Zoom(options);
  4463. };
  4464. /*
  4465. * @class Control.Scale
  4466. * @aka L.Control.Scale
  4467. * @inherits Control
  4468. *
  4469. * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`.
  4470. *
  4471. * @example
  4472. *
  4473. * ```js
  4474. * L.control.scale().addTo(map);
  4475. * ```
  4476. */
  4477. var Scale = Control.extend({
  4478. // @section
  4479. // @aka Control.Scale options
  4480. options: {
  4481. position: 'bottomleft',
  4482. // @option maxWidth: Number = 100
  4483. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4484. maxWidth: 100,
  4485. // @option metric: Boolean = True
  4486. // Whether to show the metric scale line (m/km).
  4487. metric: true,
  4488. // @option imperial: Boolean = True
  4489. // Whether to show the imperial scale line (mi/ft).
  4490. imperial: true
  4491. // @option updateWhenIdle: Boolean = false
  4492. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4493. },
  4494. onAdd: function (map) {
  4495. var className = 'leaflet-control-scale',
  4496. container = create$1('div', className),
  4497. options = this.options;
  4498. this._addScales(options, className + '-line', container);
  4499. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4500. map.whenReady(this._update, this);
  4501. return container;
  4502. },
  4503. onRemove: function (map) {
  4504. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4505. },
  4506. _addScales: function (options, className, container) {
  4507. if (options.metric) {
  4508. this._mScale = create$1('div', className, container);
  4509. }
  4510. if (options.imperial) {
  4511. this._iScale = create$1('div', className, container);
  4512. }
  4513. },
  4514. _update: function () {
  4515. var map = this._map,
  4516. y = map.getSize().y / 2;
  4517. var maxMeters = map.distance(
  4518. map.containerPointToLatLng([0, y]),
  4519. map.containerPointToLatLng([this.options.maxWidth, y]));
  4520. this._updateScales(maxMeters);
  4521. },
  4522. _updateScales: function (maxMeters) {
  4523. if (this.options.metric && maxMeters) {
  4524. this._updateMetric(maxMeters);
  4525. }
  4526. if (this.options.imperial && maxMeters) {
  4527. this._updateImperial(maxMeters);
  4528. }
  4529. },
  4530. _updateMetric: function (maxMeters) {
  4531. var meters = this._getRoundNum(maxMeters),
  4532. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4533. this._updateScale(this._mScale, label, meters / maxMeters);
  4534. },
  4535. _updateImperial: function (maxMeters) {
  4536. var maxFeet = maxMeters * 3.2808399,
  4537. maxMiles, miles, feet;
  4538. if (maxFeet > 5280) {
  4539. maxMiles = maxFeet / 5280;
  4540. miles = this._getRoundNum(maxMiles);
  4541. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4542. } else {
  4543. feet = this._getRoundNum(maxFeet);
  4544. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4545. }
  4546. },
  4547. _updateScale: function (scale, text, ratio) {
  4548. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4549. scale.innerHTML = text;
  4550. },
  4551. _getRoundNum: function (num) {
  4552. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4553. d = num / pow10;
  4554. d = d >= 10 ? 10 :
  4555. d >= 5 ? 5 :
  4556. d >= 3 ? 3 :
  4557. d >= 2 ? 2 : 1;
  4558. return pow10 * d;
  4559. }
  4560. });
  4561. // @factory L.control.scale(options?: Control.Scale options)
  4562. // Creates an scale control with the given options.
  4563. var scale = function (options) {
  4564. return new Scale(options);
  4565. };
  4566. /*
  4567. * @class Control.Attribution
  4568. * @aka L.Control.Attribution
  4569. * @inherits Control
  4570. *
  4571. * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control.
  4572. */
  4573. var Attribution = Control.extend({
  4574. // @section
  4575. // @aka Control.Attribution options
  4576. options: {
  4577. position: 'bottomright',
  4578. // @option prefix: String = 'Leaflet'
  4579. // The HTML text shown before the attributions. Pass `false` to disable.
  4580. prefix: '<a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4581. },
  4582. initialize: function (options) {
  4583. setOptions(this, options);
  4584. this._attributions = {};
  4585. },
  4586. onAdd: function (map) {
  4587. map.attributionControl = this;
  4588. this._container = create$1('div', 'leaflet-control-attribution');
  4589. disableClickPropagation(this._container);
  4590. // TODO ugly, refactor
  4591. for (var i in map._layers) {
  4592. if (map._layers[i].getAttribution) {
  4593. this.addAttribution(map._layers[i].getAttribution());
  4594. }
  4595. }
  4596. this._update();
  4597. return this._container;
  4598. },
  4599. // @method setPrefix(prefix: String): this
  4600. // Sets the text before the attributions.
  4601. setPrefix: function (prefix) {
  4602. this.options.prefix = prefix;
  4603. this._update();
  4604. return this;
  4605. },
  4606. // @method addAttribution(text: String): this
  4607. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4608. addAttribution: function (text) {
  4609. if (!text) { return this; }
  4610. if (!this._attributions[text]) {
  4611. this._attributions[text] = 0;
  4612. }
  4613. this._attributions[text]++;
  4614. this._update();
  4615. return this;
  4616. },
  4617. // @method removeAttribution(text: String): this
  4618. // Removes an attribution text.
  4619. removeAttribution: function (text) {
  4620. if (!text) { return this; }
  4621. if (this._attributions[text]) {
  4622. this._attributions[text]--;
  4623. this._update();
  4624. }
  4625. return this;
  4626. },
  4627. _update: function () {
  4628. if (!this._map) { return; }
  4629. var attribs = [];
  4630. for (var i in this._attributions) {
  4631. if (this._attributions[i]) {
  4632. attribs.push(i);
  4633. }
  4634. }
  4635. var prefixAndAttribs = [];
  4636. if (this.options.prefix) {
  4637. prefixAndAttribs.push(this.options.prefix);
  4638. }
  4639. if (attribs.length) {
  4640. prefixAndAttribs.push(attribs.join(', '));
  4641. }
  4642. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4643. }
  4644. });
  4645. // @namespace Map
  4646. // @section Control options
  4647. // @option attributionControl: Boolean = true
  4648. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4649. Map.mergeOptions({
  4650. attributionControl: true
  4651. });
  4652. Map.addInitHook(function () {
  4653. if (this.options.attributionControl) {
  4654. new Attribution().addTo(this);
  4655. }
  4656. });
  4657. // @namespace Control.Attribution
  4658. // @factory L.control.attribution(options: Control.Attribution options)
  4659. // Creates an attribution control.
  4660. var attribution = function (options) {
  4661. return new Attribution(options);
  4662. };
  4663. Control.Layers = Layers;
  4664. Control.Zoom = Zoom;
  4665. Control.Scale = Scale;
  4666. Control.Attribution = Attribution;
  4667. control.layers = layers;
  4668. control.zoom = zoom;
  4669. control.scale = scale;
  4670. control.attribution = attribution;
  4671. /*
  4672. L.Handler is a base class for handler classes that are used internally to inject
  4673. interaction features like dragging to classes like Map and Marker.
  4674. */
  4675. // @class Handler
  4676. // @aka L.Handler
  4677. // Abstract class for map interaction handlers
  4678. var Handler = Class.extend({
  4679. initialize: function (map) {
  4680. this._map = map;
  4681. },
  4682. // @method enable(): this
  4683. // Enables the handler
  4684. enable: function () {
  4685. if (this._enabled) { return this; }
  4686. this._enabled = true;
  4687. this.addHooks();
  4688. return this;
  4689. },
  4690. // @method disable(): this
  4691. // Disables the handler
  4692. disable: function () {
  4693. if (!this._enabled) { return this; }
  4694. this._enabled = false;
  4695. this.removeHooks();
  4696. return this;
  4697. },
  4698. // @method enabled(): Boolean
  4699. // Returns `true` if the handler is enabled
  4700. enabled: function () {
  4701. return !!this._enabled;
  4702. }
  4703. // @section Extension methods
  4704. // Classes inheriting from `Handler` must implement the two following methods:
  4705. // @method addHooks()
  4706. // Called when the handler is enabled, should add event hooks.
  4707. // @method removeHooks()
  4708. // Called when the handler is disabled, should remove the event hooks added previously.
  4709. });
  4710. // @section There is static function which can be called without instantiating L.Handler:
  4711. // @function addTo(map: Map, name: String): this
  4712. // Adds a new Handler to the given map with the given name.
  4713. Handler.addTo = function (map, name) {
  4714. map.addHandler(name, this);
  4715. return this;
  4716. };
  4717. var Mixin = {Events: Events};
  4718. /*
  4719. * @class Draggable
  4720. * @aka L.Draggable
  4721. * @inherits Evented
  4722. *
  4723. * A class for making DOM elements draggable (including touch support).
  4724. * Used internally for map and marker dragging. Only works for elements
  4725. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4726. *
  4727. * @example
  4728. * ```js
  4729. * var draggable = new L.Draggable(elementToDrag);
  4730. * draggable.enable();
  4731. * ```
  4732. */
  4733. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4734. var END = {
  4735. mousedown: 'mouseup',
  4736. touchstart: 'touchend',
  4737. pointerdown: 'touchend',
  4738. MSPointerDown: 'touchend'
  4739. };
  4740. var MOVE = {
  4741. mousedown: 'mousemove',
  4742. touchstart: 'touchmove',
  4743. pointerdown: 'touchmove',
  4744. MSPointerDown: 'touchmove'
  4745. };
  4746. var Draggable = Evented.extend({
  4747. options: {
  4748. // @section
  4749. // @aka Draggable options
  4750. // @option clickTolerance: Number = 3
  4751. // The max number of pixels a user can shift the mouse pointer during a click
  4752. // for it to be considered a valid click (as opposed to a mouse drag).
  4753. clickTolerance: 3
  4754. },
  4755. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4756. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4757. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4758. setOptions(this, options);
  4759. this._element = element;
  4760. this._dragStartTarget = dragStartTarget || element;
  4761. this._preventOutline = preventOutline$$1;
  4762. },
  4763. // @method enable()
  4764. // Enables the dragging ability
  4765. enable: function () {
  4766. if (this._enabled) { return; }
  4767. on(this._dragStartTarget, START, this._onDown, this);
  4768. this._enabled = true;
  4769. },
  4770. // @method disable()
  4771. // Disables the dragging ability
  4772. disable: function () {
  4773. if (!this._enabled) { return; }
  4774. // If we're currently dragging this draggable,
  4775. // disabling it counts as first ending the drag.
  4776. if (Draggable._dragging === this) {
  4777. this.finishDrag();
  4778. }
  4779. off(this._dragStartTarget, START, this._onDown, this);
  4780. this._enabled = false;
  4781. this._moved = false;
  4782. },
  4783. _onDown: function (e) {
  4784. // Ignore simulated events, since we handle both touch and
  4785. // mouse explicitly; otherwise we risk getting duplicates of
  4786. // touch events, see #4315.
  4787. // Also ignore the event if disabled; this happens in IE11
  4788. // under some circumstances, see #3666.
  4789. if (e._simulated || !this._enabled) { return; }
  4790. this._moved = false;
  4791. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4792. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4793. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4794. if (this._preventOutline) {
  4795. preventOutline(this._element);
  4796. }
  4797. disableImageDrag();
  4798. disableTextSelection();
  4799. if (this._moving) { return; }
  4800. // @event down: Event
  4801. // Fired when a drag is about to start.
  4802. this.fire('down');
  4803. var first = e.touches ? e.touches[0] : e,
  4804. sizedParent = getSizedParentNode(this._element);
  4805. this._startPoint = new Point(first.clientX, first.clientY);
  4806. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4807. this._parentScale = getScale(sizedParent);
  4808. on(document, MOVE[e.type], this._onMove, this);
  4809. on(document, END[e.type], this._onUp, this);
  4810. },
  4811. _onMove: function (e) {
  4812. // Ignore simulated events, since we handle both touch and
  4813. // mouse explicitly; otherwise we risk getting duplicates of
  4814. // touch events, see #4315.
  4815. // Also ignore the event if disabled; this happens in IE11
  4816. // under some circumstances, see #3666.
  4817. if (e._simulated || !this._enabled) { return; }
  4818. if (e.touches && e.touches.length > 1) {
  4819. this._moved = true;
  4820. return;
  4821. }
  4822. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4823. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4824. if (!offset.x && !offset.y) { return; }
  4825. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4826. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4827. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4828. // and we can use the cached value for the scale.
  4829. offset.x /= this._parentScale.x;
  4830. offset.y /= this._parentScale.y;
  4831. preventDefault(e);
  4832. if (!this._moved) {
  4833. // @event dragstart: Event
  4834. // Fired when a drag starts
  4835. this.fire('dragstart');
  4836. this._moved = true;
  4837. this._startPos = getPosition(this._element).subtract(offset);
  4838. addClass(document.body, 'leaflet-dragging');
  4839. this._lastTarget = e.target || e.srcElement;
  4840. // IE and Edge do not give the <use> element, so fetch it
  4841. // if necessary
  4842. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  4843. this._lastTarget = this._lastTarget.correspondingUseElement;
  4844. }
  4845. addClass(this._lastTarget, 'leaflet-drag-target');
  4846. }
  4847. this._newPos = this._startPos.add(offset);
  4848. this._moving = true;
  4849. cancelAnimFrame(this._animRequest);
  4850. this._lastEvent = e;
  4851. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4852. },
  4853. _updatePosition: function () {
  4854. var e = {originalEvent: this._lastEvent};
  4855. // @event predrag: Event
  4856. // Fired continuously during dragging *before* each corresponding
  4857. // update of the element's position.
  4858. this.fire('predrag', e);
  4859. setPosition(this._element, this._newPos);
  4860. // @event drag: Event
  4861. // Fired continuously during dragging.
  4862. this.fire('drag', e);
  4863. },
  4864. _onUp: function (e) {
  4865. // Ignore simulated events, since we handle both touch and
  4866. // mouse explicitly; otherwise we risk getting duplicates of
  4867. // touch events, see #4315.
  4868. // Also ignore the event if disabled; this happens in IE11
  4869. // under some circumstances, see #3666.
  4870. if (e._simulated || !this._enabled) { return; }
  4871. this.finishDrag();
  4872. },
  4873. finishDrag: function () {
  4874. removeClass(document.body, 'leaflet-dragging');
  4875. if (this._lastTarget) {
  4876. removeClass(this._lastTarget, 'leaflet-drag-target');
  4877. this._lastTarget = null;
  4878. }
  4879. for (var i in MOVE) {
  4880. off(document, MOVE[i], this._onMove, this);
  4881. off(document, END[i], this._onUp, this);
  4882. }
  4883. enableImageDrag();
  4884. enableTextSelection();
  4885. if (this._moved && this._moving) {
  4886. // ensure drag is not fired after dragend
  4887. cancelAnimFrame(this._animRequest);
  4888. // @event dragend: DragEndEvent
  4889. // Fired when the drag ends.
  4890. this.fire('dragend', {
  4891. distance: this._newPos.distanceTo(this._startPos)
  4892. });
  4893. }
  4894. this._moving = false;
  4895. Draggable._dragging = false;
  4896. }
  4897. });
  4898. /*
  4899. * @namespace LineUtil
  4900. *
  4901. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  4902. */
  4903. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4904. // Improves rendering performance dramatically by lessening the number of points to draw.
  4905. // @function simplify(points: Point[], tolerance: Number): Point[]
  4906. // Dramatically reduces the number of points in a polyline while retaining
  4907. // its shape and returns a new array of simplified points, using the
  4908. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4909. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4910. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4911. // simplification (lesser value means higher quality but slower and with more points).
  4912. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4913. function simplify(points, tolerance) {
  4914. if (!tolerance || !points.length) {
  4915. return points.slice();
  4916. }
  4917. var sqTolerance = tolerance * tolerance;
  4918. // stage 1: vertex reduction
  4919. points = _reducePoints(points, sqTolerance);
  4920. // stage 2: Douglas-Peucker simplification
  4921. points = _simplifyDP(points, sqTolerance);
  4922. return points;
  4923. }
  4924. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4925. // Returns the distance between point `p` and segment `p1` to `p2`.
  4926. function pointToSegmentDistance(p, p1, p2) {
  4927. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4928. }
  4929. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4930. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4931. function closestPointOnSegment(p, p1, p2) {
  4932. return _sqClosestPointOnSegment(p, p1, p2);
  4933. }
  4934. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4935. function _simplifyDP(points, sqTolerance) {
  4936. var len = points.length,
  4937. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4938. markers = new ArrayConstructor(len);
  4939. markers[0] = markers[len - 1] = 1;
  4940. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4941. var i,
  4942. newPoints = [];
  4943. for (i = 0; i < len; i++) {
  4944. if (markers[i]) {
  4945. newPoints.push(points[i]);
  4946. }
  4947. }
  4948. return newPoints;
  4949. }
  4950. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4951. var maxSqDist = 0,
  4952. index, i, sqDist;
  4953. for (i = first + 1; i <= last - 1; i++) {
  4954. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4955. if (sqDist > maxSqDist) {
  4956. index = i;
  4957. maxSqDist = sqDist;
  4958. }
  4959. }
  4960. if (maxSqDist > sqTolerance) {
  4961. markers[index] = 1;
  4962. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4963. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4964. }
  4965. }
  4966. // reduce points that are too close to each other to a single point
  4967. function _reducePoints(points, sqTolerance) {
  4968. var reducedPoints = [points[0]];
  4969. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4970. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4971. reducedPoints.push(points[i]);
  4972. prev = i;
  4973. }
  4974. }
  4975. if (prev < len - 1) {
  4976. reducedPoints.push(points[len - 1]);
  4977. }
  4978. return reducedPoints;
  4979. }
  4980. var _lastCode;
  4981. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  4982. // Clips the segment a to b by rectangular bounds with the
  4983. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  4984. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  4985. // points that are on the screen or near, increasing performance.
  4986. function clipSegment(a, b, bounds, useLastCode, round) {
  4987. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  4988. codeB = _getBitCode(b, bounds),
  4989. codeOut, p, newCode;
  4990. // save 2nd code to avoid calculating it on the next segment
  4991. _lastCode = codeB;
  4992. while (true) {
  4993. // if a,b is inside the clip window (trivial accept)
  4994. if (!(codeA | codeB)) {
  4995. return [a, b];
  4996. }
  4997. // if a,b is outside the clip window (trivial reject)
  4998. if (codeA & codeB) {
  4999. return false;
  5000. }
  5001. // other cases
  5002. codeOut = codeA || codeB;
  5003. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  5004. newCode = _getBitCode(p, bounds);
  5005. if (codeOut === codeA) {
  5006. a = p;
  5007. codeA = newCode;
  5008. } else {
  5009. b = p;
  5010. codeB = newCode;
  5011. }
  5012. }
  5013. }
  5014. function _getEdgeIntersection(a, b, code, bounds, round) {
  5015. var dx = b.x - a.x,
  5016. dy = b.y - a.y,
  5017. min = bounds.min,
  5018. max = bounds.max,
  5019. x, y;
  5020. if (code & 8) { // top
  5021. x = a.x + dx * (max.y - a.y) / dy;
  5022. y = max.y;
  5023. } else if (code & 4) { // bottom
  5024. x = a.x + dx * (min.y - a.y) / dy;
  5025. y = min.y;
  5026. } else if (code & 2) { // right
  5027. x = max.x;
  5028. y = a.y + dy * (max.x - a.x) / dx;
  5029. } else if (code & 1) { // left
  5030. x = min.x;
  5031. y = a.y + dy * (min.x - a.x) / dx;
  5032. }
  5033. return new Point(x, y, round);
  5034. }
  5035. function _getBitCode(p, bounds) {
  5036. var code = 0;
  5037. if (p.x < bounds.min.x) { // left
  5038. code |= 1;
  5039. } else if (p.x > bounds.max.x) { // right
  5040. code |= 2;
  5041. }
  5042. if (p.y < bounds.min.y) { // bottom
  5043. code |= 4;
  5044. } else if (p.y > bounds.max.y) { // top
  5045. code |= 8;
  5046. }
  5047. return code;
  5048. }
  5049. // square distance (to avoid unnecessary Math.sqrt calls)
  5050. function _sqDist(p1, p2) {
  5051. var dx = p2.x - p1.x,
  5052. dy = p2.y - p1.y;
  5053. return dx * dx + dy * dy;
  5054. }
  5055. // return closest point on segment or distance to that point
  5056. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5057. var x = p1.x,
  5058. y = p1.y,
  5059. dx = p2.x - x,
  5060. dy = p2.y - y,
  5061. dot = dx * dx + dy * dy,
  5062. t;
  5063. if (dot > 0) {
  5064. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5065. if (t > 1) {
  5066. x = p2.x;
  5067. y = p2.y;
  5068. } else if (t > 0) {
  5069. x += dx * t;
  5070. y += dy * t;
  5071. }
  5072. }
  5073. dx = p.x - x;
  5074. dy = p.y - y;
  5075. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5076. }
  5077. // @function isFlat(latlngs: LatLng[]): Boolean
  5078. // Returns true if `latlngs` is a flat array, false is nested.
  5079. function isFlat(latlngs) {
  5080. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5081. }
  5082. function _flat(latlngs) {
  5083. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5084. return isFlat(latlngs);
  5085. }
  5086. var LineUtil = (Object.freeze || Object)({
  5087. simplify: simplify,
  5088. pointToSegmentDistance: pointToSegmentDistance,
  5089. closestPointOnSegment: closestPointOnSegment,
  5090. clipSegment: clipSegment,
  5091. _getEdgeIntersection: _getEdgeIntersection,
  5092. _getBitCode: _getBitCode,
  5093. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5094. isFlat: isFlat,
  5095. _flat: _flat
  5096. });
  5097. /*
  5098. * @namespace PolyUtil
  5099. * Various utility functions for polygon geometries.
  5100. */
  5101. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5102. * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
  5103. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5104. * performance. Note that polygon points needs different algorithm for clipping
  5105. * than polyline, so there's a separate method for it.
  5106. */
  5107. function clipPolygon(points, bounds, round) {
  5108. var clippedPoints,
  5109. edges = [1, 4, 2, 8],
  5110. i, j, k,
  5111. a, b,
  5112. len, edge, p;
  5113. for (i = 0, len = points.length; i < len; i++) {
  5114. points[i]._code = _getBitCode(points[i], bounds);
  5115. }
  5116. // for each edge (left, bottom, right, top)
  5117. for (k = 0; k < 4; k++) {
  5118. edge = edges[k];
  5119. clippedPoints = [];
  5120. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5121. a = points[i];
  5122. b = points[j];
  5123. // if a is inside the clip window
  5124. if (!(a._code & edge)) {
  5125. // if b is outside the clip window (a->b goes out of screen)
  5126. if (b._code & edge) {
  5127. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5128. p._code = _getBitCode(p, bounds);
  5129. clippedPoints.push(p);
  5130. }
  5131. clippedPoints.push(a);
  5132. // else if b is inside the clip window (a->b enters the screen)
  5133. } else if (!(b._code & edge)) {
  5134. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5135. p._code = _getBitCode(p, bounds);
  5136. clippedPoints.push(p);
  5137. }
  5138. }
  5139. points = clippedPoints;
  5140. }
  5141. return points;
  5142. }
  5143. var PolyUtil = (Object.freeze || Object)({
  5144. clipPolygon: clipPolygon
  5145. });
  5146. /*
  5147. * @namespace Projection
  5148. * @section
  5149. * Leaflet comes with a set of already defined Projections out of the box:
  5150. *
  5151. * @projection L.Projection.LonLat
  5152. *
  5153. * Equirectangular, or Plate Carree projection — the most simple projection,
  5154. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5155. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5156. * `EPSG:4326` and `Simple` CRS.
  5157. */
  5158. var LonLat = {
  5159. project: function (latlng) {
  5160. return new Point(latlng.lng, latlng.lat);
  5161. },
  5162. unproject: function (point) {
  5163. return new LatLng(point.y, point.x);
  5164. },
  5165. bounds: new Bounds([-180, -90], [180, 90])
  5166. };
  5167. /*
  5168. * @namespace Projection
  5169. * @projection L.Projection.Mercator
  5170. *
  5171. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5172. */
  5173. var Mercator = {
  5174. R: 6378137,
  5175. R_MINOR: 6356752.314245179,
  5176. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5177. project: function (latlng) {
  5178. var d = Math.PI / 180,
  5179. r = this.R,
  5180. y = latlng.lat * d,
  5181. tmp = this.R_MINOR / r,
  5182. e = Math.sqrt(1 - tmp * tmp),
  5183. con = e * Math.sin(y);
  5184. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5185. y = -r * Math.log(Math.max(ts, 1E-10));
  5186. return new Point(latlng.lng * d * r, y);
  5187. },
  5188. unproject: function (point) {
  5189. var d = 180 / Math.PI,
  5190. r = this.R,
  5191. tmp = this.R_MINOR / r,
  5192. e = Math.sqrt(1 - tmp * tmp),
  5193. ts = Math.exp(-point.y / r),
  5194. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5195. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5196. con = e * Math.sin(phi);
  5197. con = Math.pow((1 - con) / (1 + con), e / 2);
  5198. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5199. phi += dphi;
  5200. }
  5201. return new LatLng(phi * d, point.x * d / r);
  5202. }
  5203. };
  5204. /*
  5205. * @class Projection
  5206. * An object with methods for projecting geographical coordinates of the world onto
  5207. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5208. * @property bounds: Bounds
  5209. * The bounds (specified in CRS units) where the projection is valid
  5210. * @method project(latlng: LatLng): Point
  5211. * Projects geographical coordinates into a 2D point.
  5212. * Only accepts actual `L.LatLng` instances, not arrays.
  5213. * @method unproject(point: Point): LatLng
  5214. * The inverse of `project`. Projects a 2D point into a geographical location.
  5215. * Only accepts actual `L.Point` instances, not arrays.
  5216. * Note that the projection instances do not inherit from Leafet's `Class` object,
  5217. * and can't be instantiated. Also, new classes can't inherit from them,
  5218. * and methods can't be added to them with the `include` function.
  5219. */
  5220. var index = (Object.freeze || Object)({
  5221. LonLat: LonLat,
  5222. Mercator: Mercator,
  5223. SphericalMercator: SphericalMercator
  5224. });
  5225. /*
  5226. * @namespace CRS
  5227. * @crs L.CRS.EPSG3395
  5228. *
  5229. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5230. */
  5231. var EPSG3395 = extend({}, Earth, {
  5232. code: 'EPSG:3395',
  5233. projection: Mercator,
  5234. transformation: (function () {
  5235. var scale = 0.5 / (Math.PI * Mercator.R);
  5236. return toTransformation(scale, 0.5, -scale, 0.5);
  5237. }())
  5238. });
  5239. /*
  5240. * @namespace CRS
  5241. * @crs L.CRS.EPSG4326
  5242. *
  5243. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5244. *
  5245. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5246. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5247. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5248. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5249. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5250. */
  5251. var EPSG4326 = extend({}, Earth, {
  5252. code: 'EPSG:4326',
  5253. projection: LonLat,
  5254. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5255. });
  5256. /*
  5257. * @namespace CRS
  5258. * @crs L.CRS.Simple
  5259. *
  5260. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5261. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5262. * axis should still be inverted (going from bottom to top). `distance()` returns
  5263. * simple euclidean distance.
  5264. */
  5265. var Simple = extend({}, CRS, {
  5266. projection: LonLat,
  5267. transformation: toTransformation(1, 0, -1, 0),
  5268. scale: function (zoom) {
  5269. return Math.pow(2, zoom);
  5270. },
  5271. zoom: function (scale) {
  5272. return Math.log(scale) / Math.LN2;
  5273. },
  5274. distance: function (latlng1, latlng2) {
  5275. var dx = latlng2.lng - latlng1.lng,
  5276. dy = latlng2.lat - latlng1.lat;
  5277. return Math.sqrt(dx * dx + dy * dy);
  5278. },
  5279. infinite: true
  5280. });
  5281. CRS.Earth = Earth;
  5282. CRS.EPSG3395 = EPSG3395;
  5283. CRS.EPSG3857 = EPSG3857;
  5284. CRS.EPSG900913 = EPSG900913;
  5285. CRS.EPSG4326 = EPSG4326;
  5286. CRS.Simple = Simple;
  5287. /*
  5288. * @class Layer
  5289. * @inherits Evented
  5290. * @aka L.Layer
  5291. * @aka ILayer
  5292. *
  5293. * A set of methods from the Layer base class that all Leaflet layers use.
  5294. * Inherits all methods, options and events from `L.Evented`.
  5295. *
  5296. * @example
  5297. *
  5298. * ```js
  5299. * var layer = L.marker(latlng).addTo(map);
  5300. * layer.addTo(map);
  5301. * layer.remove();
  5302. * ```
  5303. *
  5304. * @event add: Event
  5305. * Fired after the layer is added to a map
  5306. *
  5307. * @event remove: Event
  5308. * Fired after the layer is removed from a map
  5309. */
  5310. var Layer = Evented.extend({
  5311. // Classes extending `L.Layer` will inherit the following options:
  5312. options: {
  5313. // @option pane: String = 'overlayPane'
  5314. // By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.
  5315. pane: 'overlayPane',
  5316. // @option attribution: String = null
  5317. // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.
  5318. attribution: null,
  5319. bubblingMouseEvents: true
  5320. },
  5321. /* @section
  5322. * Classes extending `L.Layer` will inherit the following methods:
  5323. *
  5324. * @method addTo(map: Map|LayerGroup): this
  5325. * Adds the layer to the given map or layer group.
  5326. */
  5327. addTo: function (map) {
  5328. map.addLayer(this);
  5329. return this;
  5330. },
  5331. // @method remove: this
  5332. // Removes the layer from the map it is currently active on.
  5333. remove: function () {
  5334. return this.removeFrom(this._map || this._mapToAdd);
  5335. },
  5336. // @method removeFrom(map: Map): this
  5337. // Removes the layer from the given map
  5338. removeFrom: function (obj) {
  5339. if (obj) {
  5340. obj.removeLayer(this);
  5341. }
  5342. return this;
  5343. },
  5344. // @method getPane(name? : String): HTMLElement
  5345. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5346. getPane: function (name) {
  5347. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5348. },
  5349. addInteractiveTarget: function (targetEl) {
  5350. this._map._targets[stamp(targetEl)] = this;
  5351. return this;
  5352. },
  5353. removeInteractiveTarget: function (targetEl) {
  5354. delete this._map._targets[stamp(targetEl)];
  5355. return this;
  5356. },
  5357. // @method getAttribution: String
  5358. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5359. getAttribution: function () {
  5360. return this.options.attribution;
  5361. },
  5362. _layerAdd: function (e) {
  5363. var map = e.target;
  5364. // check in case layer gets added and then removed before the map is ready
  5365. if (!map.hasLayer(this)) { return; }
  5366. this._map = map;
  5367. this._zoomAnimated = map._zoomAnimated;
  5368. if (this.getEvents) {
  5369. var events = this.getEvents();
  5370. map.on(events, this);
  5371. this.once('remove', function () {
  5372. map.off(events, this);
  5373. }, this);
  5374. }
  5375. this.onAdd(map);
  5376. if (this.getAttribution && map.attributionControl) {
  5377. map.attributionControl.addAttribution(this.getAttribution());
  5378. }
  5379. this.fire('add');
  5380. map.fire('layeradd', {layer: this});
  5381. }
  5382. });
  5383. /* @section Extension methods
  5384. * @uninheritable
  5385. *
  5386. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5387. *
  5388. * @method onAdd(map: Map): this
  5389. * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer).
  5390. *
  5391. * @method onRemove(map: Map): this
  5392. * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer).
  5393. *
  5394. * @method getEvents(): Object
  5395. * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer.
  5396. *
  5397. * @method getAttribution(): String
  5398. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5399. *
  5400. * @method beforeAdd(map: Map): this
  5401. * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.
  5402. */
  5403. /* @namespace Map
  5404. * @section Layer events
  5405. *
  5406. * @event layeradd: LayerEvent
  5407. * Fired when a new layer is added to the map.
  5408. *
  5409. * @event layerremove: LayerEvent
  5410. * Fired when some layer is removed from the map
  5411. *
  5412. * @section Methods for Layers and Controls
  5413. */
  5414. Map.include({
  5415. // @method addLayer(layer: Layer): this
  5416. // Adds the given layer to the map
  5417. addLayer: function (layer) {
  5418. if (!layer._layerAdd) {
  5419. throw new Error('The provided object is not a Layer.');
  5420. }
  5421. var id = stamp(layer);
  5422. if (this._layers[id]) { return this; }
  5423. this._layers[id] = layer;
  5424. layer._mapToAdd = this;
  5425. if (layer.beforeAdd) {
  5426. layer.beforeAdd(this);
  5427. }
  5428. this.whenReady(layer._layerAdd, layer);
  5429. return this;
  5430. },
  5431. // @method removeLayer(layer: Layer): this
  5432. // Removes the given layer from the map.
  5433. removeLayer: function (layer) {
  5434. var id = stamp(layer);
  5435. if (!this._layers[id]) { return this; }
  5436. if (this._loaded) {
  5437. layer.onRemove(this);
  5438. }
  5439. if (layer.getAttribution && this.attributionControl) {
  5440. this.attributionControl.removeAttribution(layer.getAttribution());
  5441. }
  5442. delete this._layers[id];
  5443. if (this._loaded) {
  5444. this.fire('layerremove', {layer: layer});
  5445. layer.fire('remove');
  5446. }
  5447. layer._map = layer._mapToAdd = null;
  5448. return this;
  5449. },
  5450. // @method hasLayer(layer: Layer): Boolean
  5451. // Returns `true` if the given layer is currently added to the map
  5452. hasLayer: function (layer) {
  5453. return !!layer && (stamp(layer) in this._layers);
  5454. },
  5455. /* @method eachLayer(fn: Function, context?: Object): this
  5456. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5457. * ```
  5458. * map.eachLayer(function(layer){
  5459. * layer.bindPopup('Hello');
  5460. * });
  5461. * ```
  5462. */
  5463. eachLayer: function (method, context) {
  5464. for (var i in this._layers) {
  5465. method.call(context, this._layers[i]);
  5466. }
  5467. return this;
  5468. },
  5469. _addLayers: function (layers) {
  5470. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5471. for (var i = 0, len = layers.length; i < len; i++) {
  5472. this.addLayer(layers[i]);
  5473. }
  5474. },
  5475. _addZoomLimit: function (layer) {
  5476. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5477. this._zoomBoundLayers[stamp(layer)] = layer;
  5478. this._updateZoomLevels();
  5479. }
  5480. },
  5481. _removeZoomLimit: function (layer) {
  5482. var id = stamp(layer);
  5483. if (this._zoomBoundLayers[id]) {
  5484. delete this._zoomBoundLayers[id];
  5485. this._updateZoomLevels();
  5486. }
  5487. },
  5488. _updateZoomLevels: function () {
  5489. var minZoom = Infinity,
  5490. maxZoom = -Infinity,
  5491. oldZoomSpan = this._getZoomSpan();
  5492. for (var i in this._zoomBoundLayers) {
  5493. var options = this._zoomBoundLayers[i].options;
  5494. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5495. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5496. }
  5497. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5498. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5499. // @section Map state change events
  5500. // @event zoomlevelschange: Event
  5501. // Fired when the number of zoomlevels on the map is changed due
  5502. // to adding or removing a layer.
  5503. if (oldZoomSpan !== this._getZoomSpan()) {
  5504. this.fire('zoomlevelschange');
  5505. }
  5506. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5507. this.setZoom(this._layersMaxZoom);
  5508. }
  5509. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5510. this.setZoom(this._layersMinZoom);
  5511. }
  5512. }
  5513. });
  5514. /*
  5515. * @class LayerGroup
  5516. * @aka L.LayerGroup
  5517. * @inherits Layer
  5518. *
  5519. * Used to group several layers and handle them as one. If you add it to the map,
  5520. * any layers added or removed from the group will be added/removed on the map as
  5521. * well. Extends `Layer`.
  5522. *
  5523. * @example
  5524. *
  5525. * ```js
  5526. * L.layerGroup([marker1, marker2])
  5527. * .addLayer(polyline)
  5528. * .addTo(map);
  5529. * ```
  5530. */
  5531. var LayerGroup = Layer.extend({
  5532. initialize: function (layers, options) {
  5533. setOptions(this, options);
  5534. this._layers = {};
  5535. var i, len;
  5536. if (layers) {
  5537. for (i = 0, len = layers.length; i < len; i++) {
  5538. this.addLayer(layers[i]);
  5539. }
  5540. }
  5541. },
  5542. // @method addLayer(layer: Layer): this
  5543. // Adds the given layer to the group.
  5544. addLayer: function (layer) {
  5545. var id = this.getLayerId(layer);
  5546. this._layers[id] = layer;
  5547. if (this._map) {
  5548. this._map.addLayer(layer);
  5549. }
  5550. return this;
  5551. },
  5552. // @method removeLayer(layer: Layer): this
  5553. // Removes the given layer from the group.
  5554. // @alternative
  5555. // @method removeLayer(id: Number): this
  5556. // Removes the layer with the given internal ID from the group.
  5557. removeLayer: function (layer) {
  5558. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5559. if (this._map && this._layers[id]) {
  5560. this._map.removeLayer(this._layers[id]);
  5561. }
  5562. delete this._layers[id];
  5563. return this;
  5564. },
  5565. // @method hasLayer(layer: Layer): Boolean
  5566. // Returns `true` if the given layer is currently added to the group.
  5567. // @alternative
  5568. // @method hasLayer(id: Number): Boolean
  5569. // Returns `true` if the given internal ID is currently added to the group.
  5570. hasLayer: function (layer) {
  5571. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5572. },
  5573. // @method clearLayers(): this
  5574. // Removes all the layers from the group.
  5575. clearLayers: function () {
  5576. return this.eachLayer(this.removeLayer, this);
  5577. },
  5578. // @method invoke(methodName: String, …): this
  5579. // Calls `methodName` on every layer contained in this group, passing any
  5580. // additional parameters. Has no effect if the layers contained do not
  5581. // implement `methodName`.
  5582. invoke: function (methodName) {
  5583. var args = Array.prototype.slice.call(arguments, 1),
  5584. i, layer;
  5585. for (i in this._layers) {
  5586. layer = this._layers[i];
  5587. if (layer[methodName]) {
  5588. layer[methodName].apply(layer, args);
  5589. }
  5590. }
  5591. return this;
  5592. },
  5593. onAdd: function (map) {
  5594. this.eachLayer(map.addLayer, map);
  5595. },
  5596. onRemove: function (map) {
  5597. this.eachLayer(map.removeLayer, map);
  5598. },
  5599. // @method eachLayer(fn: Function, context?: Object): this
  5600. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5601. // ```js
  5602. // group.eachLayer(function (layer) {
  5603. // layer.bindPopup('Hello');
  5604. // });
  5605. // ```
  5606. eachLayer: function (method, context) {
  5607. for (var i in this._layers) {
  5608. method.call(context, this._layers[i]);
  5609. }
  5610. return this;
  5611. },
  5612. // @method getLayer(id: Number): Layer
  5613. // Returns the layer with the given internal ID.
  5614. getLayer: function (id) {
  5615. return this._layers[id];
  5616. },
  5617. // @method getLayers(): Layer[]
  5618. // Returns an array of all the layers added to the group.
  5619. getLayers: function () {
  5620. var layers = [];
  5621. this.eachLayer(layers.push, layers);
  5622. return layers;
  5623. },
  5624. // @method setZIndex(zIndex: Number): this
  5625. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5626. setZIndex: function (zIndex) {
  5627. return this.invoke('setZIndex', zIndex);
  5628. },
  5629. // @method getLayerId(layer: Layer): Number
  5630. // Returns the internal ID for a layer
  5631. getLayerId: function (layer) {
  5632. return stamp(layer);
  5633. }
  5634. });
  5635. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5636. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5637. var layerGroup = function (layers, options) {
  5638. return new LayerGroup(layers, options);
  5639. };
  5640. /*
  5641. * @class FeatureGroup
  5642. * @aka L.FeatureGroup
  5643. * @inherits LayerGroup
  5644. *
  5645. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5646. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5647. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5648. * handler, it will handle events from any of the layers. This includes mouse events
  5649. * and custom events.
  5650. * * Has `layeradd` and `layerremove` events
  5651. *
  5652. * @example
  5653. *
  5654. * ```js
  5655. * L.featureGroup([marker1, marker2, polyline])
  5656. * .bindPopup('Hello world!')
  5657. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5658. * .addTo(map);
  5659. * ```
  5660. */
  5661. var FeatureGroup = LayerGroup.extend({
  5662. addLayer: function (layer) {
  5663. if (this.hasLayer(layer)) {
  5664. return this;
  5665. }
  5666. layer.addEventParent(this);
  5667. LayerGroup.prototype.addLayer.call(this, layer);
  5668. // @event layeradd: LayerEvent
  5669. // Fired when a layer is added to this `FeatureGroup`
  5670. return this.fire('layeradd', {layer: layer});
  5671. },
  5672. removeLayer: function (layer) {
  5673. if (!this.hasLayer(layer)) {
  5674. return this;
  5675. }
  5676. if (layer in this._layers) {
  5677. layer = this._layers[layer];
  5678. }
  5679. layer.removeEventParent(this);
  5680. LayerGroup.prototype.removeLayer.call(this, layer);
  5681. // @event layerremove: LayerEvent
  5682. // Fired when a layer is removed from this `FeatureGroup`
  5683. return this.fire('layerremove', {layer: layer});
  5684. },
  5685. // @method setStyle(style: Path options): this
  5686. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5687. setStyle: function (style) {
  5688. return this.invoke('setStyle', style);
  5689. },
  5690. // @method bringToFront(): this
  5691. // Brings the layer group to the top of all other layers
  5692. bringToFront: function () {
  5693. return this.invoke('bringToFront');
  5694. },
  5695. // @method bringToBack(): this
  5696. // Brings the layer group to the back of all other layers
  5697. bringToBack: function () {
  5698. return this.invoke('bringToBack');
  5699. },
  5700. // @method getBounds(): LatLngBounds
  5701. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5702. getBounds: function () {
  5703. var bounds = new LatLngBounds();
  5704. for (var id in this._layers) {
  5705. var layer = this._layers[id];
  5706. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5707. }
  5708. return bounds;
  5709. }
  5710. });
  5711. // @factory L.featureGroup(layers: Layer[])
  5712. // Create a feature group, optionally given an initial set of layers.
  5713. var featureGroup = function (layers) {
  5714. return new FeatureGroup(layers);
  5715. };
  5716. /*
  5717. * @class Icon
  5718. * @aka L.Icon
  5719. *
  5720. * Represents an icon to provide when creating a marker.
  5721. *
  5722. * @example
  5723. *
  5724. * ```js
  5725. * var myIcon = L.icon({
  5726. * iconUrl: 'my-icon.png',
  5727. * iconRetinaUrl: 'my-icon@2x.png',
  5728. * iconSize: [38, 95],
  5729. * iconAnchor: [22, 94],
  5730. * popupAnchor: [-3, -76],
  5731. * shadowUrl: 'my-icon-shadow.png',
  5732. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5733. * shadowSize: [68, 95],
  5734. * shadowAnchor: [22, 94]
  5735. * });
  5736. *
  5737. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5738. * ```
  5739. *
  5740. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5741. *
  5742. */
  5743. var Icon = Class.extend({
  5744. /* @section
  5745. * @aka Icon options
  5746. *
  5747. * @option iconUrl: String = null
  5748. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5749. *
  5750. * @option iconRetinaUrl: String = null
  5751. * The URL to a retina sized version of the icon image (absolute or relative to your
  5752. * script path). Used for Retina screen devices.
  5753. *
  5754. * @option iconSize: Point = null
  5755. * Size of the icon image in pixels.
  5756. *
  5757. * @option iconAnchor: Point = null
  5758. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5759. * will be aligned so that this point is at the marker's geographical location. Centered
  5760. * by default if size is specified, also can be set in CSS with negative margins.
  5761. *
  5762. * @option popupAnchor: Point = [0, 0]
  5763. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5764. *
  5765. * @option tooltipAnchor: Point = [0, 0]
  5766. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5767. *
  5768. * @option shadowUrl: String = null
  5769. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5770. *
  5771. * @option shadowRetinaUrl: String = null
  5772. *
  5773. * @option shadowSize: Point = null
  5774. * Size of the shadow image in pixels.
  5775. *
  5776. * @option shadowAnchor: Point = null
  5777. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5778. * as iconAnchor if not specified).
  5779. *
  5780. * @option className: String = ''
  5781. * A custom class name to assign to both icon and shadow images. Empty by default.
  5782. */
  5783. options: {
  5784. popupAnchor: [0, 0],
  5785. tooltipAnchor: [0, 0]
  5786. },
  5787. initialize: function (options) {
  5788. setOptions(this, options);
  5789. },
  5790. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5791. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5792. // styled according to the options.
  5793. createIcon: function (oldIcon) {
  5794. return this._createIcon('icon', oldIcon);
  5795. },
  5796. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5797. // As `createIcon`, but for the shadow beneath it.
  5798. createShadow: function (oldIcon) {
  5799. return this._createIcon('shadow', oldIcon);
  5800. },
  5801. _createIcon: function (name, oldIcon) {
  5802. var src = this._getIconUrl(name);
  5803. if (!src) {
  5804. if (name === 'icon') {
  5805. throw new Error('iconUrl not set in Icon options (see the docs).');
  5806. }
  5807. return null;
  5808. }
  5809. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5810. this._setIconStyles(img, name);
  5811. return img;
  5812. },
  5813. _setIconStyles: function (img, name) {
  5814. var options = this.options;
  5815. var sizeOption = options[name + 'Size'];
  5816. if (typeof sizeOption === 'number') {
  5817. sizeOption = [sizeOption, sizeOption];
  5818. }
  5819. var size = toPoint(sizeOption),
  5820. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5821. size && size.divideBy(2, true));
  5822. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5823. if (anchor) {
  5824. img.style.marginLeft = (-anchor.x) + 'px';
  5825. img.style.marginTop = (-anchor.y) + 'px';
  5826. }
  5827. if (size) {
  5828. img.style.width = size.x + 'px';
  5829. img.style.height = size.y + 'px';
  5830. }
  5831. },
  5832. _createImg: function (src, el) {
  5833. el = el || document.createElement('img');
  5834. el.src = src;
  5835. return el;
  5836. },
  5837. _getIconUrl: function (name) {
  5838. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5839. }
  5840. });
  5841. // @factory L.icon(options: Icon options)
  5842. // Creates an icon instance with the given options.
  5843. function icon(options) {
  5844. return new Icon(options);
  5845. }
  5846. /*
  5847. * @miniclass Icon.Default (Icon)
  5848. * @aka L.Icon.Default
  5849. * @section
  5850. *
  5851. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5852. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5853. * releases.
  5854. *
  5855. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5856. * (which is a set of `Icon options`).
  5857. *
  5858. * If you want to _completely_ replace the default icon, override the
  5859. * `L.Marker.prototype.options.icon` with your own icon instead.
  5860. */
  5861. var IconDefault = Icon.extend({
  5862. options: {
  5863. iconUrl: 'marker-icon.png',
  5864. iconRetinaUrl: 'marker-icon-2x.png',
  5865. shadowUrl: 'marker-shadow.png',
  5866. iconSize: [25, 41],
  5867. iconAnchor: [12, 41],
  5868. popupAnchor: [1, -34],
  5869. tooltipAnchor: [16, -28],
  5870. shadowSize: [41, 41]
  5871. },
  5872. _getIconUrl: function (name) {
  5873. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5874. IconDefault.imagePath = this._detectIconPath();
  5875. }
  5876. // @option imagePath: String
  5877. // `Icon.Default` will try to auto-detect the location of the
  5878. // blue icon images. If you are placing these images in a non-standard
  5879. // way, set this option to point to the right path.
  5880. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5881. },
  5882. _detectIconPath: function () {
  5883. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5884. var path = getStyle(el, 'background-image') ||
  5885. getStyle(el, 'backgroundImage'); // IE8
  5886. document.body.removeChild(el);
  5887. if (path === null || path.indexOf('url') !== 0) {
  5888. path = '';
  5889. } else {
  5890. path = path.replace(/^url\(["']?/, '').replace(/marker-icon\.png["']?\)$/, '');
  5891. }
  5892. return path;
  5893. }
  5894. });
  5895. /*
  5896. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5897. */
  5898. /* @namespace Marker
  5899. * @section Interaction handlers
  5900. *
  5901. * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example:
  5902. *
  5903. * ```js
  5904. * marker.dragging.disable();
  5905. * ```
  5906. *
  5907. * @property dragging: Handler
  5908. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5909. */
  5910. var MarkerDrag = Handler.extend({
  5911. initialize: function (marker) {
  5912. this._marker = marker;
  5913. },
  5914. addHooks: function () {
  5915. var icon = this._marker._icon;
  5916. if (!this._draggable) {
  5917. this._draggable = new Draggable(icon, icon, true);
  5918. }
  5919. this._draggable.on({
  5920. dragstart: this._onDragStart,
  5921. predrag: this._onPreDrag,
  5922. drag: this._onDrag,
  5923. dragend: this._onDragEnd
  5924. }, this).enable();
  5925. addClass(icon, 'leaflet-marker-draggable');
  5926. },
  5927. removeHooks: function () {
  5928. this._draggable.off({
  5929. dragstart: this._onDragStart,
  5930. predrag: this._onPreDrag,
  5931. drag: this._onDrag,
  5932. dragend: this._onDragEnd
  5933. }, this).disable();
  5934. if (this._marker._icon) {
  5935. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5936. }
  5937. },
  5938. moved: function () {
  5939. return this._draggable && this._draggable._moved;
  5940. },
  5941. _adjustPan: function (e) {
  5942. var marker = this._marker,
  5943. map = marker._map,
  5944. speed = this._marker.options.autoPanSpeed,
  5945. padding = this._marker.options.autoPanPadding,
  5946. iconPos = getPosition(marker._icon),
  5947. bounds = map.getPixelBounds(),
  5948. origin = map.getPixelOrigin();
  5949. var panBounds = toBounds(
  5950. bounds.min._subtract(origin).add(padding),
  5951. bounds.max._subtract(origin).subtract(padding)
  5952. );
  5953. if (!panBounds.contains(iconPos)) {
  5954. // Compute incremental movement
  5955. var movement = toPoint(
  5956. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  5957. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  5958. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  5959. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  5960. ).multiplyBy(speed);
  5961. map.panBy(movement, {animate: false});
  5962. this._draggable._newPos._add(movement);
  5963. this._draggable._startPos._add(movement);
  5964. setPosition(marker._icon, this._draggable._newPos);
  5965. this._onDrag(e);
  5966. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5967. }
  5968. },
  5969. _onDragStart: function () {
  5970. // @section Dragging events
  5971. // @event dragstart: Event
  5972. // Fired when the user starts dragging the marker.
  5973. // @event movestart: Event
  5974. // Fired when the marker starts moving (because of dragging).
  5975. this._oldLatLng = this._marker.getLatLng();
  5976. this._marker
  5977. .closePopup()
  5978. .fire('movestart')
  5979. .fire('dragstart');
  5980. },
  5981. _onPreDrag: function (e) {
  5982. if (this._marker.options.autoPan) {
  5983. cancelAnimFrame(this._panRequest);
  5984. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5985. }
  5986. },
  5987. _onDrag: function (e) {
  5988. var marker = this._marker,
  5989. shadow = marker._shadow,
  5990. iconPos = getPosition(marker._icon),
  5991. latlng = marker._map.layerPointToLatLng(iconPos);
  5992. // update shadow position
  5993. if (shadow) {
  5994. setPosition(shadow, iconPos);
  5995. }
  5996. marker._latlng = latlng;
  5997. e.latlng = latlng;
  5998. e.oldLatLng = this._oldLatLng;
  5999. // @event drag: Event
  6000. // Fired repeatedly while the user drags the marker.
  6001. marker
  6002. .fire('move', e)
  6003. .fire('drag', e);
  6004. },
  6005. _onDragEnd: function (e) {
  6006. // @event dragend: DragEndEvent
  6007. // Fired when the user stops dragging the marker.
  6008. cancelAnimFrame(this._panRequest);
  6009. // @event moveend: Event
  6010. // Fired when the marker stops moving (because of dragging).
  6011. delete this._oldLatLng;
  6012. this._marker
  6013. .fire('moveend')
  6014. .fire('dragend', e);
  6015. }
  6016. });
  6017. /*
  6018. * @class Marker
  6019. * @inherits Interactive layer
  6020. * @aka L.Marker
  6021. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6022. *
  6023. * @example
  6024. *
  6025. * ```js
  6026. * L.marker([50.5, 30.5]).addTo(map);
  6027. * ```
  6028. */
  6029. var Marker = Layer.extend({
  6030. // @section
  6031. // @aka Marker options
  6032. options: {
  6033. // @option icon: Icon = *
  6034. // Icon instance to use for rendering the marker.
  6035. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6036. // If not specified, a common instance of `L.Icon.Default` is used.
  6037. icon: new IconDefault(),
  6038. // Option inherited from "Interactive layer" abstract class
  6039. interactive: true,
  6040. // @option keyboard: Boolean = true
  6041. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6042. keyboard: true,
  6043. // @option title: String = ''
  6044. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6045. title: '',
  6046. // @option alt: String = ''
  6047. // Text for the `alt` attribute of the icon image (useful for accessibility).
  6048. alt: '',
  6049. // @option zIndexOffset: Number = 0
  6050. // By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).
  6051. zIndexOffset: 0,
  6052. // @option opacity: Number = 1.0
  6053. // The opacity of the marker.
  6054. opacity: 1,
  6055. // @option riseOnHover: Boolean = false
  6056. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6057. riseOnHover: false,
  6058. // @option riseOffset: Number = 250
  6059. // The z-index offset used for the `riseOnHover` feature.
  6060. riseOffset: 250,
  6061. // @option pane: String = 'markerPane'
  6062. // `Map pane` where the markers icon will be added.
  6063. pane: 'markerPane',
  6064. // @option pane: String = 'shadowPane'
  6065. // `Map pane` where the markers shadow will be added.
  6066. shadowPane: 'shadowPane',
  6067. // @option bubblingMouseEvents: Boolean = false
  6068. // When `true`, a mouse event on this marker will trigger the same event on the map
  6069. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6070. bubblingMouseEvents: false,
  6071. // @section Draggable marker options
  6072. // @option draggable: Boolean = false
  6073. // Whether the marker is draggable with mouse/touch or not.
  6074. draggable: false,
  6075. // @option autoPan: Boolean = false
  6076. // Whether to pan the map when dragging this marker near its edge or not.
  6077. autoPan: false,
  6078. // @option autoPanPadding: Point = Point(50, 50)
  6079. // Distance (in pixels to the left/right and to the top/bottom) of the
  6080. // map edge to start panning the map.
  6081. autoPanPadding: [50, 50],
  6082. // @option autoPanSpeed: Number = 10
  6083. // Number of pixels the map should pan by.
  6084. autoPanSpeed: 10
  6085. },
  6086. /* @section
  6087. *
  6088. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6089. */
  6090. initialize: function (latlng, options) {
  6091. setOptions(this, options);
  6092. this._latlng = toLatLng(latlng);
  6093. },
  6094. onAdd: function (map) {
  6095. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6096. if (this._zoomAnimated) {
  6097. map.on('zoomanim', this._animateZoom, this);
  6098. }
  6099. this._initIcon();
  6100. this.update();
  6101. },
  6102. onRemove: function (map) {
  6103. if (this.dragging && this.dragging.enabled()) {
  6104. this.options.draggable = true;
  6105. this.dragging.removeHooks();
  6106. }
  6107. delete this.dragging;
  6108. if (this._zoomAnimated) {
  6109. map.off('zoomanim', this._animateZoom, this);
  6110. }
  6111. this._removeIcon();
  6112. this._removeShadow();
  6113. },
  6114. getEvents: function () {
  6115. return {
  6116. zoom: this.update,
  6117. viewreset: this.update
  6118. };
  6119. },
  6120. // @method getLatLng: LatLng
  6121. // Returns the current geographical position of the marker.
  6122. getLatLng: function () {
  6123. return this._latlng;
  6124. },
  6125. // @method setLatLng(latlng: LatLng): this
  6126. // Changes the marker position to the given point.
  6127. setLatLng: function (latlng) {
  6128. var oldLatLng = this._latlng;
  6129. this._latlng = toLatLng(latlng);
  6130. this.update();
  6131. // @event move: Event
  6132. // Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  6133. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6134. },
  6135. // @method setZIndexOffset(offset: Number): this
  6136. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6137. setZIndexOffset: function (offset) {
  6138. this.options.zIndexOffset = offset;
  6139. return this.update();
  6140. },
  6141. // @method getIcon: Icon
  6142. // Returns the current icon used by the marker
  6143. getIcon: function () {
  6144. return this.options.icon;
  6145. },
  6146. // @method setIcon(icon: Icon): this
  6147. // Changes the marker icon.
  6148. setIcon: function (icon) {
  6149. this.options.icon = icon;
  6150. if (this._map) {
  6151. this._initIcon();
  6152. this.update();
  6153. }
  6154. if (this._popup) {
  6155. this.bindPopup(this._popup, this._popup.options);
  6156. }
  6157. return this;
  6158. },
  6159. getElement: function () {
  6160. return this._icon;
  6161. },
  6162. update: function () {
  6163. if (this._icon && this._map) {
  6164. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6165. this._setPos(pos);
  6166. }
  6167. return this;
  6168. },
  6169. _initIcon: function () {
  6170. var options = this.options,
  6171. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6172. var icon = options.icon.createIcon(this._icon),
  6173. addIcon = false;
  6174. // if we're not reusing the icon, remove the old one and init new one
  6175. if (icon !== this._icon) {
  6176. if (this._icon) {
  6177. this._removeIcon();
  6178. }
  6179. addIcon = true;
  6180. if (options.title) {
  6181. icon.title = options.title;
  6182. }
  6183. if (icon.tagName === 'IMG') {
  6184. icon.alt = options.alt || '';
  6185. }
  6186. }
  6187. addClass(icon, classToAdd);
  6188. if (options.keyboard) {
  6189. icon.tabIndex = '0';
  6190. }
  6191. this._icon = icon;
  6192. if (options.riseOnHover) {
  6193. this.on({
  6194. mouseover: this._bringToFront,
  6195. mouseout: this._resetZIndex
  6196. });
  6197. }
  6198. var newShadow = options.icon.createShadow(this._shadow),
  6199. addShadow = false;
  6200. if (newShadow !== this._shadow) {
  6201. this._removeShadow();
  6202. addShadow = true;
  6203. }
  6204. if (newShadow) {
  6205. addClass(newShadow, classToAdd);
  6206. newShadow.alt = '';
  6207. }
  6208. this._shadow = newShadow;
  6209. if (options.opacity < 1) {
  6210. this._updateOpacity();
  6211. }
  6212. if (addIcon) {
  6213. this.getPane().appendChild(this._icon);
  6214. }
  6215. this._initInteraction();
  6216. if (newShadow && addShadow) {
  6217. this.getPane(options.shadowPane).appendChild(this._shadow);
  6218. }
  6219. },
  6220. _removeIcon: function () {
  6221. if (this.options.riseOnHover) {
  6222. this.off({
  6223. mouseover: this._bringToFront,
  6224. mouseout: this._resetZIndex
  6225. });
  6226. }
  6227. remove(this._icon);
  6228. this.removeInteractiveTarget(this._icon);
  6229. this._icon = null;
  6230. },
  6231. _removeShadow: function () {
  6232. if (this._shadow) {
  6233. remove(this._shadow);
  6234. }
  6235. this._shadow = null;
  6236. },
  6237. _setPos: function (pos) {
  6238. setPosition(this._icon, pos);
  6239. if (this._shadow) {
  6240. setPosition(this._shadow, pos);
  6241. }
  6242. this._zIndex = pos.y + this.options.zIndexOffset;
  6243. this._resetZIndex();
  6244. },
  6245. _updateZIndex: function (offset) {
  6246. this._icon.style.zIndex = this._zIndex + offset;
  6247. },
  6248. _animateZoom: function (opt) {
  6249. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6250. this._setPos(pos);
  6251. },
  6252. _initInteraction: function () {
  6253. if (!this.options.interactive) { return; }
  6254. addClass(this._icon, 'leaflet-interactive');
  6255. this.addInteractiveTarget(this._icon);
  6256. if (MarkerDrag) {
  6257. var draggable = this.options.draggable;
  6258. if (this.dragging) {
  6259. draggable = this.dragging.enabled();
  6260. this.dragging.disable();
  6261. }
  6262. this.dragging = new MarkerDrag(this);
  6263. if (draggable) {
  6264. this.dragging.enable();
  6265. }
  6266. }
  6267. },
  6268. // @method setOpacity(opacity: Number): this
  6269. // Changes the opacity of the marker.
  6270. setOpacity: function (opacity) {
  6271. this.options.opacity = opacity;
  6272. if (this._map) {
  6273. this._updateOpacity();
  6274. }
  6275. return this;
  6276. },
  6277. _updateOpacity: function () {
  6278. var opacity = this.options.opacity;
  6279. if (this._icon) {
  6280. setOpacity(this._icon, opacity);
  6281. }
  6282. if (this._shadow) {
  6283. setOpacity(this._shadow, opacity);
  6284. }
  6285. },
  6286. _bringToFront: function () {
  6287. this._updateZIndex(this.options.riseOffset);
  6288. },
  6289. _resetZIndex: function () {
  6290. this._updateZIndex(0);
  6291. },
  6292. _getPopupAnchor: function () {
  6293. return this.options.icon.options.popupAnchor;
  6294. },
  6295. _getTooltipAnchor: function () {
  6296. return this.options.icon.options.tooltipAnchor;
  6297. }
  6298. });
  6299. // factory L.marker(latlng: LatLng, options? : Marker options)
  6300. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6301. // Instantiates a Marker object given a geographical point and optionally an options object.
  6302. function marker(latlng, options) {
  6303. return new Marker(latlng, options);
  6304. }
  6305. /*
  6306. * @class Path
  6307. * @aka L.Path
  6308. * @inherits Interactive layer
  6309. *
  6310. * An abstract class that contains options and constants shared between vector
  6311. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6312. */
  6313. var Path = Layer.extend({
  6314. // @section
  6315. // @aka Path options
  6316. options: {
  6317. // @option stroke: Boolean = true
  6318. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6319. stroke: true,
  6320. // @option color: String = '#3388ff'
  6321. // Stroke color
  6322. color: '#3388ff',
  6323. // @option weight: Number = 3
  6324. // Stroke width in pixels
  6325. weight: 3,
  6326. // @option opacity: Number = 1.0
  6327. // Stroke opacity
  6328. opacity: 1,
  6329. // @option lineCap: String= 'round'
  6330. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6331. lineCap: 'round',
  6332. // @option lineJoin: String = 'round'
  6333. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6334. lineJoin: 'round',
  6335. // @option dashArray: String = null
  6336. // A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
  6337. dashArray: null,
  6338. // @option dashOffset: String = null
  6339. // A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
  6340. dashOffset: null,
  6341. // @option fill: Boolean = depends
  6342. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6343. fill: false,
  6344. // @option fillColor: String = *
  6345. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6346. fillColor: null,
  6347. // @option fillOpacity: Number = 0.2
  6348. // Fill opacity.
  6349. fillOpacity: 0.2,
  6350. // @option fillRule: String = 'evenodd'
  6351. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6352. fillRule: 'evenodd',
  6353. // className: '',
  6354. // Option inherited from "Interactive layer" abstract class
  6355. interactive: true,
  6356. // @option bubblingMouseEvents: Boolean = true
  6357. // When `true`, a mouse event on this path will trigger the same event on the map
  6358. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6359. bubblingMouseEvents: true
  6360. },
  6361. beforeAdd: function (map) {
  6362. // Renderer is set here because we need to call renderer.getEvents
  6363. // before this.getEvents.
  6364. this._renderer = map.getRenderer(this);
  6365. },
  6366. onAdd: function () {
  6367. this._renderer._initPath(this);
  6368. this._reset();
  6369. this._renderer._addPath(this);
  6370. },
  6371. onRemove: function () {
  6372. this._renderer._removePath(this);
  6373. },
  6374. // @method redraw(): this
  6375. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6376. redraw: function () {
  6377. if (this._map) {
  6378. this._renderer._updatePath(this);
  6379. }
  6380. return this;
  6381. },
  6382. // @method setStyle(style: Path options): this
  6383. // Changes the appearance of a Path based on the options in the `Path options` object.
  6384. setStyle: function (style) {
  6385. setOptions(this, style);
  6386. if (this._renderer) {
  6387. this._renderer._updateStyle(this);
  6388. if (this.options.stroke && style.hasOwnProperty('weight')) {
  6389. this._updateBounds();
  6390. }
  6391. }
  6392. return this;
  6393. },
  6394. // @method bringToFront(): this
  6395. // Brings the layer to the top of all path layers.
  6396. bringToFront: function () {
  6397. if (this._renderer) {
  6398. this._renderer._bringToFront(this);
  6399. }
  6400. return this;
  6401. },
  6402. // @method bringToBack(): this
  6403. // Brings the layer to the bottom of all path layers.
  6404. bringToBack: function () {
  6405. if (this._renderer) {
  6406. this._renderer._bringToBack(this);
  6407. }
  6408. return this;
  6409. },
  6410. getElement: function () {
  6411. return this._path;
  6412. },
  6413. _reset: function () {
  6414. // defined in child classes
  6415. this._project();
  6416. this._update();
  6417. },
  6418. _clickTolerance: function () {
  6419. // used when doing hit detection for Canvas layers
  6420. return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;
  6421. }
  6422. });
  6423. /*
  6424. * @class CircleMarker
  6425. * @aka L.CircleMarker
  6426. * @inherits Path
  6427. *
  6428. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6429. */
  6430. var CircleMarker = Path.extend({
  6431. // @section
  6432. // @aka CircleMarker options
  6433. options: {
  6434. fill: true,
  6435. // @option radius: Number = 10
  6436. // Radius of the circle marker, in pixels
  6437. radius: 10
  6438. },
  6439. initialize: function (latlng, options) {
  6440. setOptions(this, options);
  6441. this._latlng = toLatLng(latlng);
  6442. this._radius = this.options.radius;
  6443. },
  6444. // @method setLatLng(latLng: LatLng): this
  6445. // Sets the position of a circle marker to a new location.
  6446. setLatLng: function (latlng) {
  6447. this._latlng = toLatLng(latlng);
  6448. this.redraw();
  6449. return this.fire('move', {latlng: this._latlng});
  6450. },
  6451. // @method getLatLng(): LatLng
  6452. // Returns the current geographical position of the circle marker
  6453. getLatLng: function () {
  6454. return this._latlng;
  6455. },
  6456. // @method setRadius(radius: Number): this
  6457. // Sets the radius of a circle marker. Units are in pixels.
  6458. setRadius: function (radius) {
  6459. this.options.radius = this._radius = radius;
  6460. return this.redraw();
  6461. },
  6462. // @method getRadius(): Number
  6463. // Returns the current radius of the circle
  6464. getRadius: function () {
  6465. return this._radius;
  6466. },
  6467. setStyle : function (options) {
  6468. var radius = options && options.radius || this._radius;
  6469. Path.prototype.setStyle.call(this, options);
  6470. this.setRadius(radius);
  6471. return this;
  6472. },
  6473. _project: function () {
  6474. this._point = this._map.latLngToLayerPoint(this._latlng);
  6475. this._updateBounds();
  6476. },
  6477. _updateBounds: function () {
  6478. var r = this._radius,
  6479. r2 = this._radiusY || r,
  6480. w = this._clickTolerance(),
  6481. p = [r + w, r2 + w];
  6482. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6483. },
  6484. _update: function () {
  6485. if (this._map) {
  6486. this._updatePath();
  6487. }
  6488. },
  6489. _updatePath: function () {
  6490. this._renderer._updateCircle(this);
  6491. },
  6492. _empty: function () {
  6493. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6494. },
  6495. // Needed by the `Canvas` renderer for interactivity
  6496. _containsPoint: function (p) {
  6497. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6498. }
  6499. });
  6500. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6501. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6502. function circleMarker(latlng, options) {
  6503. return new CircleMarker(latlng, options);
  6504. }
  6505. /*
  6506. * @class Circle
  6507. * @aka L.Circle
  6508. * @inherits CircleMarker
  6509. *
  6510. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6511. *
  6512. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6513. *
  6514. * @example
  6515. *
  6516. * ```js
  6517. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6518. * ```
  6519. */
  6520. var Circle = CircleMarker.extend({
  6521. initialize: function (latlng, options, legacyOptions) {
  6522. if (typeof options === 'number') {
  6523. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6524. options = extend({}, legacyOptions, {radius: options});
  6525. }
  6526. setOptions(this, options);
  6527. this._latlng = toLatLng(latlng);
  6528. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6529. // @section
  6530. // @aka Circle options
  6531. // @option radius: Number; Radius of the circle, in meters.
  6532. this._mRadius = this.options.radius;
  6533. },
  6534. // @method setRadius(radius: Number): this
  6535. // Sets the radius of a circle. Units are in meters.
  6536. setRadius: function (radius) {
  6537. this._mRadius = radius;
  6538. return this.redraw();
  6539. },
  6540. // @method getRadius(): Number
  6541. // Returns the current radius of a circle. Units are in meters.
  6542. getRadius: function () {
  6543. return this._mRadius;
  6544. },
  6545. // @method getBounds(): LatLngBounds
  6546. // Returns the `LatLngBounds` of the path.
  6547. getBounds: function () {
  6548. var half = [this._radius, this._radiusY || this._radius];
  6549. return new LatLngBounds(
  6550. this._map.layerPointToLatLng(this._point.subtract(half)),
  6551. this._map.layerPointToLatLng(this._point.add(half)));
  6552. },
  6553. setStyle: Path.prototype.setStyle,
  6554. _project: function () {
  6555. var lng = this._latlng.lng,
  6556. lat = this._latlng.lat,
  6557. map = this._map,
  6558. crs = map.options.crs;
  6559. if (crs.distance === Earth.distance) {
  6560. var d = Math.PI / 180,
  6561. latR = (this._mRadius / Earth.R) / d,
  6562. top = map.project([lat + latR, lng]),
  6563. bottom = map.project([lat - latR, lng]),
  6564. p = top.add(bottom).divideBy(2),
  6565. lat2 = map.unproject(p).lat,
  6566. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6567. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6568. if (isNaN(lngR) || lngR === 0) {
  6569. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6570. }
  6571. this._point = p.subtract(map.getPixelOrigin());
  6572. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6573. this._radiusY = p.y - top.y;
  6574. } else {
  6575. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6576. this._point = map.latLngToLayerPoint(this._latlng);
  6577. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6578. }
  6579. this._updateBounds();
  6580. }
  6581. });
  6582. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6583. // Instantiates a circle object given a geographical point, and an options object
  6584. // which contains the circle radius.
  6585. // @alternative
  6586. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6587. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6588. // Do not use in new applications or plugins.
  6589. function circle(latlng, options, legacyOptions) {
  6590. return new Circle(latlng, options, legacyOptions);
  6591. }
  6592. /*
  6593. * @class Polyline
  6594. * @aka L.Polyline
  6595. * @inherits Path
  6596. *
  6597. * A class for drawing polyline overlays on a map. Extends `Path`.
  6598. *
  6599. * @example
  6600. *
  6601. * ```js
  6602. * // create a red polyline from an array of LatLng points
  6603. * var latlngs = [
  6604. * [45.51, -122.68],
  6605. * [37.77, -122.43],
  6606. * [34.04, -118.2]
  6607. * ];
  6608. *
  6609. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6610. *
  6611. * // zoom the map to the polyline
  6612. * map.fitBounds(polyline.getBounds());
  6613. * ```
  6614. *
  6615. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6616. *
  6617. * ```js
  6618. * // create a red polyline from an array of arrays of LatLng points
  6619. * var latlngs = [
  6620. * [[45.51, -122.68],
  6621. * [37.77, -122.43],
  6622. * [34.04, -118.2]],
  6623. * [[40.78, -73.91],
  6624. * [41.83, -87.62],
  6625. * [32.76, -96.72]]
  6626. * ];
  6627. * ```
  6628. */
  6629. var Polyline = Path.extend({
  6630. // @section
  6631. // @aka Polyline options
  6632. options: {
  6633. // @option smoothFactor: Number = 1.0
  6634. // How much to simplify the polyline on each zoom level. More means
  6635. // better performance and smoother look, and less means more accurate representation.
  6636. smoothFactor: 1.0,
  6637. // @option noClip: Boolean = false
  6638. // Disable polyline clipping.
  6639. noClip: false
  6640. },
  6641. initialize: function (latlngs, options) {
  6642. setOptions(this, options);
  6643. this._setLatLngs(latlngs);
  6644. },
  6645. // @method getLatLngs(): LatLng[]
  6646. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6647. getLatLngs: function () {
  6648. return this._latlngs;
  6649. },
  6650. // @method setLatLngs(latlngs: LatLng[]): this
  6651. // Replaces all the points in the polyline with the given array of geographical points.
  6652. setLatLngs: function (latlngs) {
  6653. this._setLatLngs(latlngs);
  6654. return this.redraw();
  6655. },
  6656. // @method isEmpty(): Boolean
  6657. // Returns `true` if the Polyline has no LatLngs.
  6658. isEmpty: function () {
  6659. return !this._latlngs.length;
  6660. },
  6661. // @method closestLayerPoint(p: Point): Point
  6662. // Returns the point closest to `p` on the Polyline.
  6663. closestLayerPoint: function (p) {
  6664. var minDistance = Infinity,
  6665. minPoint = null,
  6666. closest = _sqClosestPointOnSegment,
  6667. p1, p2;
  6668. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6669. var points = this._parts[j];
  6670. for (var i = 1, len = points.length; i < len; i++) {
  6671. p1 = points[i - 1];
  6672. p2 = points[i];
  6673. var sqDist = closest(p, p1, p2, true);
  6674. if (sqDist < minDistance) {
  6675. minDistance = sqDist;
  6676. minPoint = closest(p, p1, p2);
  6677. }
  6678. }
  6679. }
  6680. if (minPoint) {
  6681. minPoint.distance = Math.sqrt(minDistance);
  6682. }
  6683. return minPoint;
  6684. },
  6685. // @method getCenter(): LatLng
  6686. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6687. getCenter: function () {
  6688. // throws error when not yet added to map as this center calculation requires projected coordinates
  6689. if (!this._map) {
  6690. throw new Error('Must add layer to map before using getCenter()');
  6691. }
  6692. var i, halfDist, segDist, dist, p1, p2, ratio,
  6693. points = this._rings[0],
  6694. len = points.length;
  6695. if (!len) { return null; }
  6696. // polyline centroid algorithm; only uses the first ring if there are multiple
  6697. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6698. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6699. }
  6700. // The line is so small in the current view that all points are on the same pixel.
  6701. if (halfDist === 0) {
  6702. return this._map.layerPointToLatLng(points[0]);
  6703. }
  6704. for (i = 0, dist = 0; i < len - 1; i++) {
  6705. p1 = points[i];
  6706. p2 = points[i + 1];
  6707. segDist = p1.distanceTo(p2);
  6708. dist += segDist;
  6709. if (dist > halfDist) {
  6710. ratio = (dist - halfDist) / segDist;
  6711. return this._map.layerPointToLatLng([
  6712. p2.x - ratio * (p2.x - p1.x),
  6713. p2.y - ratio * (p2.y - p1.y)
  6714. ]);
  6715. }
  6716. }
  6717. },
  6718. // @method getBounds(): LatLngBounds
  6719. // Returns the `LatLngBounds` of the path.
  6720. getBounds: function () {
  6721. return this._bounds;
  6722. },
  6723. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6724. // Adds a given point to the polyline. By default, adds to the first ring of
  6725. // the polyline in case of a multi-polyline, but can be overridden by passing
  6726. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6727. addLatLng: function (latlng, latlngs) {
  6728. latlngs = latlngs || this._defaultShape();
  6729. latlng = toLatLng(latlng);
  6730. latlngs.push(latlng);
  6731. this._bounds.extend(latlng);
  6732. return this.redraw();
  6733. },
  6734. _setLatLngs: function (latlngs) {
  6735. this._bounds = new LatLngBounds();
  6736. this._latlngs = this._convertLatLngs(latlngs);
  6737. },
  6738. _defaultShape: function () {
  6739. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6740. },
  6741. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6742. _convertLatLngs: function (latlngs) {
  6743. var result = [],
  6744. flat = isFlat(latlngs);
  6745. for (var i = 0, len = latlngs.length; i < len; i++) {
  6746. if (flat) {
  6747. result[i] = toLatLng(latlngs[i]);
  6748. this._bounds.extend(result[i]);
  6749. } else {
  6750. result[i] = this._convertLatLngs(latlngs[i]);
  6751. }
  6752. }
  6753. return result;
  6754. },
  6755. _project: function () {
  6756. var pxBounds = new Bounds();
  6757. this._rings = [];
  6758. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6759. if (this._bounds.isValid() && pxBounds.isValid()) {
  6760. this._rawPxBounds = pxBounds;
  6761. this._updateBounds();
  6762. }
  6763. },
  6764. _updateBounds: function () {
  6765. var w = this._clickTolerance(),
  6766. p = new Point(w, w);
  6767. this._pxBounds = new Bounds([
  6768. this._rawPxBounds.min.subtract(p),
  6769. this._rawPxBounds.max.add(p)
  6770. ]);
  6771. },
  6772. // recursively turns latlngs into a set of rings with projected coordinates
  6773. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6774. var flat = latlngs[0] instanceof LatLng,
  6775. len = latlngs.length,
  6776. i, ring;
  6777. if (flat) {
  6778. ring = [];
  6779. for (i = 0; i < len; i++) {
  6780. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6781. projectedBounds.extend(ring[i]);
  6782. }
  6783. result.push(ring);
  6784. } else {
  6785. for (i = 0; i < len; i++) {
  6786. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6787. }
  6788. }
  6789. },
  6790. // clip polyline by renderer bounds so that we have less to render for performance
  6791. _clipPoints: function () {
  6792. var bounds = this._renderer._bounds;
  6793. this._parts = [];
  6794. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6795. return;
  6796. }
  6797. if (this.options.noClip) {
  6798. this._parts = this._rings;
  6799. return;
  6800. }
  6801. var parts = this._parts,
  6802. i, j, k, len, len2, segment, points;
  6803. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6804. points = this._rings[i];
  6805. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6806. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6807. if (!segment) { continue; }
  6808. parts[k] = parts[k] || [];
  6809. parts[k].push(segment[0]);
  6810. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6811. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6812. parts[k].push(segment[1]);
  6813. k++;
  6814. }
  6815. }
  6816. }
  6817. },
  6818. // simplify each clipped part of the polyline for performance
  6819. _simplifyPoints: function () {
  6820. var parts = this._parts,
  6821. tolerance = this.options.smoothFactor;
  6822. for (var i = 0, len = parts.length; i < len; i++) {
  6823. parts[i] = simplify(parts[i], tolerance);
  6824. }
  6825. },
  6826. _update: function () {
  6827. if (!this._map) { return; }
  6828. this._clipPoints();
  6829. this._simplifyPoints();
  6830. this._updatePath();
  6831. },
  6832. _updatePath: function () {
  6833. this._renderer._updatePoly(this);
  6834. },
  6835. // Needed by the `Canvas` renderer for interactivity
  6836. _containsPoint: function (p, closed) {
  6837. var i, j, k, len, len2, part,
  6838. w = this._clickTolerance();
  6839. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6840. // hit detection for polylines
  6841. for (i = 0, len = this._parts.length; i < len; i++) {
  6842. part = this._parts[i];
  6843. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6844. if (!closed && (j === 0)) { continue; }
  6845. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6846. return true;
  6847. }
  6848. }
  6849. }
  6850. return false;
  6851. }
  6852. });
  6853. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6854. // Instantiates a polyline object given an array of geographical points and
  6855. // optionally an options object. You can create a `Polyline` object with
  6856. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6857. // of geographic points.
  6858. function polyline(latlngs, options) {
  6859. return new Polyline(latlngs, options);
  6860. }
  6861. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6862. Polyline._flat = _flat;
  6863. /*
  6864. * @class Polygon
  6865. * @aka L.Polygon
  6866. * @inherits Polyline
  6867. *
  6868. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6869. *
  6870. * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.
  6871. *
  6872. *
  6873. * @example
  6874. *
  6875. * ```js
  6876. * // create a red polygon from an array of LatLng points
  6877. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6878. *
  6879. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6880. *
  6881. * // zoom the map to the polygon
  6882. * map.fitBounds(polygon.getBounds());
  6883. * ```
  6884. *
  6885. * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:
  6886. *
  6887. * ```js
  6888. * var latlngs = [
  6889. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6890. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6891. * ];
  6892. * ```
  6893. *
  6894. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6895. *
  6896. * ```js
  6897. * var latlngs = [
  6898. * [ // first polygon
  6899. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6900. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6901. * ],
  6902. * [ // second polygon
  6903. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6904. * ]
  6905. * ];
  6906. * ```
  6907. */
  6908. var Polygon = Polyline.extend({
  6909. options: {
  6910. fill: true
  6911. },
  6912. isEmpty: function () {
  6913. return !this._latlngs.length || !this._latlngs[0].length;
  6914. },
  6915. getCenter: function () {
  6916. // throws error when not yet added to map as this center calculation requires projected coordinates
  6917. if (!this._map) {
  6918. throw new Error('Must add layer to map before using getCenter()');
  6919. }
  6920. var i, j, p1, p2, f, area, x, y, center,
  6921. points = this._rings[0],
  6922. len = points.length;
  6923. if (!len) { return null; }
  6924. // polygon centroid algorithm; only uses the first ring if there are multiple
  6925. area = x = y = 0;
  6926. for (i = 0, j = len - 1; i < len; j = i++) {
  6927. p1 = points[i];
  6928. p2 = points[j];
  6929. f = p1.y * p2.x - p2.y * p1.x;
  6930. x += (p1.x + p2.x) * f;
  6931. y += (p1.y + p2.y) * f;
  6932. area += f * 3;
  6933. }
  6934. if (area === 0) {
  6935. // Polygon is so small that all points are on same pixel.
  6936. center = points[0];
  6937. } else {
  6938. center = [x / area, y / area];
  6939. }
  6940. return this._map.layerPointToLatLng(center);
  6941. },
  6942. _convertLatLngs: function (latlngs) {
  6943. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6944. len = result.length;
  6945. // remove last point if it equals first one
  6946. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6947. result.pop();
  6948. }
  6949. return result;
  6950. },
  6951. _setLatLngs: function (latlngs) {
  6952. Polyline.prototype._setLatLngs.call(this, latlngs);
  6953. if (isFlat(this._latlngs)) {
  6954. this._latlngs = [this._latlngs];
  6955. }
  6956. },
  6957. _defaultShape: function () {
  6958. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6959. },
  6960. _clipPoints: function () {
  6961. // polygons need a different clipping algorithm so we redefine that
  6962. var bounds = this._renderer._bounds,
  6963. w = this.options.weight,
  6964. p = new Point(w, w);
  6965. // increase clip padding by stroke width to avoid stroke on clip edges
  6966. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6967. this._parts = [];
  6968. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6969. return;
  6970. }
  6971. if (this.options.noClip) {
  6972. this._parts = this._rings;
  6973. return;
  6974. }
  6975. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6976. clipped = clipPolygon(this._rings[i], bounds, true);
  6977. if (clipped.length) {
  6978. this._parts.push(clipped);
  6979. }
  6980. }
  6981. },
  6982. _updatePath: function () {
  6983. this._renderer._updatePoly(this, true);
  6984. },
  6985. // Needed by the `Canvas` renderer for interactivity
  6986. _containsPoint: function (p) {
  6987. var inside = false,
  6988. part, p1, p2, i, j, k, len, len2;
  6989. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6990. // ray casting algorithm for detecting if point is in polygon
  6991. for (i = 0, len = this._parts.length; i < len; i++) {
  6992. part = this._parts[i];
  6993. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6994. p1 = part[j];
  6995. p2 = part[k];
  6996. if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
  6997. inside = !inside;
  6998. }
  6999. }
  7000. }
  7001. // also check if it's on polygon stroke
  7002. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7003. }
  7004. });
  7005. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7006. function polygon(latlngs, options) {
  7007. return new Polygon(latlngs, options);
  7008. }
  7009. /*
  7010. * @class GeoJSON
  7011. * @aka L.GeoJSON
  7012. * @inherits FeatureGroup
  7013. *
  7014. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7015. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7016. *
  7017. * @example
  7018. *
  7019. * ```js
  7020. * L.geoJSON(data, {
  7021. * style: function (feature) {
  7022. * return {color: feature.properties.color};
  7023. * }
  7024. * }).bindPopup(function (layer) {
  7025. * return layer.feature.properties.description;
  7026. * }).addTo(map);
  7027. * ```
  7028. */
  7029. var GeoJSON = FeatureGroup.extend({
  7030. /* @section
  7031. * @aka GeoJSON options
  7032. *
  7033. * @option pointToLayer: Function = *
  7034. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7035. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7036. * The default is to spawn a default `Marker`:
  7037. * ```js
  7038. * function(geoJsonPoint, latlng) {
  7039. * return L.marker(latlng);
  7040. * }
  7041. * ```
  7042. *
  7043. * @option style: Function = *
  7044. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7045. * called internally when data is added.
  7046. * The default value is to not override any defaults:
  7047. * ```js
  7048. * function (geoJsonFeature) {
  7049. * return {}
  7050. * }
  7051. * ```
  7052. *
  7053. * @option onEachFeature: Function = *
  7054. * A `Function` that will be called once for each created `Feature`, after it has
  7055. * been created and styled. Useful for attaching events and popups to features.
  7056. * The default is to do nothing with the newly created layers:
  7057. * ```js
  7058. * function (feature, layer) {}
  7059. * ```
  7060. *
  7061. * @option filter: Function = *
  7062. * A `Function` that will be used to decide whether to include a feature or not.
  7063. * The default is to include all features:
  7064. * ```js
  7065. * function (geoJsonFeature) {
  7066. * return true;
  7067. * }
  7068. * ```
  7069. * Note: dynamically changing the `filter` option will have effect only on newly
  7070. * added data. It will _not_ re-evaluate already included features.
  7071. *
  7072. * @option coordsToLatLng: Function = *
  7073. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7074. * The default is the `coordsToLatLng` static method.
  7075. */
  7076. initialize: function (geojson, options) {
  7077. setOptions(this, options);
  7078. this._layers = {};
  7079. if (geojson) {
  7080. this.addData(geojson);
  7081. }
  7082. },
  7083. // @method addData( <GeoJSON> data ): this
  7084. // Adds a GeoJSON object to the layer.
  7085. addData: function (geojson) {
  7086. var features = isArray(geojson) ? geojson : geojson.features,
  7087. i, len, feature;
  7088. if (features) {
  7089. for (i = 0, len = features.length; i < len; i++) {
  7090. // only add this if geometry or geometries are set and not null
  7091. feature = features[i];
  7092. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7093. this.addData(feature);
  7094. }
  7095. }
  7096. return this;
  7097. }
  7098. var options = this.options;
  7099. if (options.filter && !options.filter(geojson)) { return this; }
  7100. var layer = geometryToLayer(geojson, options);
  7101. if (!layer) {
  7102. return this;
  7103. }
  7104. layer.feature = asFeature(geojson);
  7105. layer.defaultOptions = layer.options;
  7106. this.resetStyle(layer);
  7107. if (options.onEachFeature) {
  7108. options.onEachFeature(geojson, layer);
  7109. }
  7110. return this.addLayer(layer);
  7111. },
  7112. // @method resetStyle( <Path> layer ): this
  7113. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7114. resetStyle: function (layer) {
  7115. // reset any custom styles
  7116. layer.options = extend({}, layer.defaultOptions);
  7117. this._setLayerStyle(layer, this.options.style);
  7118. return this;
  7119. },
  7120. // @method setStyle( <Function> style ): this
  7121. // Changes styles of GeoJSON vector layers with the given style function.
  7122. setStyle: function (style) {
  7123. return this.eachLayer(function (layer) {
  7124. this._setLayerStyle(layer, style);
  7125. }, this);
  7126. },
  7127. _setLayerStyle: function (layer, style) {
  7128. if (layer.setStyle) {
  7129. if (typeof style === 'function') {
  7130. style = style(layer.feature);
  7131. }
  7132. layer.setStyle(style);
  7133. }
  7134. }
  7135. });
  7136. // @section
  7137. // There are several static functions which can be called without instantiating L.GeoJSON:
  7138. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7139. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7140. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7141. // functions if provided as options.
  7142. function geometryToLayer(geojson, options) {
  7143. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7144. coords = geometry ? geometry.coordinates : null,
  7145. layers = [],
  7146. pointToLayer = options && options.pointToLayer,
  7147. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7148. latlng, latlngs, i, len;
  7149. if (!coords && !geometry) {
  7150. return null;
  7151. }
  7152. switch (geometry.type) {
  7153. case 'Point':
  7154. latlng = _coordsToLatLng(coords);
  7155. return pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);
  7156. case 'MultiPoint':
  7157. for (i = 0, len = coords.length; i < len; i++) {
  7158. latlng = _coordsToLatLng(coords[i]);
  7159. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));
  7160. }
  7161. return new FeatureGroup(layers);
  7162. case 'LineString':
  7163. case 'MultiLineString':
  7164. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7165. return new Polyline(latlngs, options);
  7166. case 'Polygon':
  7167. case 'MultiPolygon':
  7168. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7169. return new Polygon(latlngs, options);
  7170. case 'GeometryCollection':
  7171. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7172. var layer = geometryToLayer({
  7173. geometry: geometry.geometries[i],
  7174. type: 'Feature',
  7175. properties: geojson.properties
  7176. }, options);
  7177. if (layer) {
  7178. layers.push(layer);
  7179. }
  7180. }
  7181. return new FeatureGroup(layers);
  7182. default:
  7183. throw new Error('Invalid GeoJSON object.');
  7184. }
  7185. }
  7186. // @function coordsToLatLng(coords: Array): LatLng
  7187. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7188. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7189. function coordsToLatLng(coords) {
  7190. return new LatLng(coords[1], coords[0], coords[2]);
  7191. }
  7192. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7193. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7194. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7195. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7196. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7197. var latlngs = [];
  7198. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7199. latlng = levelsDeep ?
  7200. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7201. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7202. latlngs.push(latlng);
  7203. }
  7204. return latlngs;
  7205. }
  7206. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  7207. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7208. function latLngToCoords(latlng, precision) {
  7209. precision = typeof precision === 'number' ? precision : 6;
  7210. return latlng.alt !== undefined ?
  7211. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7212. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7213. }
  7214. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  7215. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7216. // `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default.
  7217. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7218. var coords = [];
  7219. for (var i = 0, len = latlngs.length; i < len; i++) {
  7220. coords.push(levelsDeep ?
  7221. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  7222. latLngToCoords(latlngs[i], precision));
  7223. }
  7224. if (!levelsDeep && closed) {
  7225. coords.push(coords[0]);
  7226. }
  7227. return coords;
  7228. }
  7229. function getFeature(layer, newGeometry) {
  7230. return layer.feature ?
  7231. extend({}, layer.feature, {geometry: newGeometry}) :
  7232. asFeature(newGeometry);
  7233. }
  7234. // @function asFeature(geojson: Object): Object
  7235. // Normalize GeoJSON geometries/features into GeoJSON features.
  7236. function asFeature(geojson) {
  7237. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7238. return geojson;
  7239. }
  7240. return {
  7241. type: 'Feature',
  7242. properties: {},
  7243. geometry: geojson
  7244. };
  7245. }
  7246. var PointToGeoJSON = {
  7247. toGeoJSON: function (precision) {
  7248. return getFeature(this, {
  7249. type: 'Point',
  7250. coordinates: latLngToCoords(this.getLatLng(), precision)
  7251. });
  7252. }
  7253. };
  7254. // @namespace Marker
  7255. // @method toGeoJSON(precision?: Number): Object
  7256. // `precision` is the number of decimal places for coordinates.
  7257. // The default value is 6 places.
  7258. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7259. Marker.include(PointToGeoJSON);
  7260. // @namespace CircleMarker
  7261. // @method toGeoJSON(precision?: Number): Object
  7262. // `precision` is the number of decimal places for coordinates.
  7263. // The default value is 6 places.
  7264. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7265. Circle.include(PointToGeoJSON);
  7266. CircleMarker.include(PointToGeoJSON);
  7267. // @namespace Polyline
  7268. // @method toGeoJSON(precision?: Number): Object
  7269. // `precision` is the number of decimal places for coordinates.
  7270. // The default value is 6 places.
  7271. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7272. Polyline.include({
  7273. toGeoJSON: function (precision) {
  7274. var multi = !isFlat(this._latlngs);
  7275. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7276. return getFeature(this, {
  7277. type: (multi ? 'Multi' : '') + 'LineString',
  7278. coordinates: coords
  7279. });
  7280. }
  7281. });
  7282. // @namespace Polygon
  7283. // @method toGeoJSON(precision?: Number): Object
  7284. // `precision` is the number of decimal places for coordinates.
  7285. // The default value is 6 places.
  7286. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7287. Polygon.include({
  7288. toGeoJSON: function (precision) {
  7289. var holes = !isFlat(this._latlngs),
  7290. multi = holes && !isFlat(this._latlngs[0]);
  7291. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7292. if (!holes) {
  7293. coords = [coords];
  7294. }
  7295. return getFeature(this, {
  7296. type: (multi ? 'Multi' : '') + 'Polygon',
  7297. coordinates: coords
  7298. });
  7299. }
  7300. });
  7301. // @namespace LayerGroup
  7302. LayerGroup.include({
  7303. toMultiPoint: function (precision) {
  7304. var coords = [];
  7305. this.eachLayer(function (layer) {
  7306. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7307. });
  7308. return getFeature(this, {
  7309. type: 'MultiPoint',
  7310. coordinates: coords
  7311. });
  7312. },
  7313. // @method toGeoJSON(precision?: Number): Object
  7314. // `precision` is the number of decimal places for coordinates.
  7315. // The default value is 6 places.
  7316. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7317. toGeoJSON: function (precision) {
  7318. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7319. if (type === 'MultiPoint') {
  7320. return this.toMultiPoint(precision);
  7321. }
  7322. var isGeometryCollection = type === 'GeometryCollection',
  7323. jsons = [];
  7324. this.eachLayer(function (layer) {
  7325. if (layer.toGeoJSON) {
  7326. var json = layer.toGeoJSON(precision);
  7327. if (isGeometryCollection) {
  7328. jsons.push(json.geometry);
  7329. } else {
  7330. var feature = asFeature(json);
  7331. // Squash nested feature collections
  7332. if (feature.type === 'FeatureCollection') {
  7333. jsons.push.apply(jsons, feature.features);
  7334. } else {
  7335. jsons.push(feature);
  7336. }
  7337. }
  7338. }
  7339. });
  7340. if (isGeometryCollection) {
  7341. return getFeature(this, {
  7342. geometries: jsons,
  7343. type: 'GeometryCollection'
  7344. });
  7345. }
  7346. return {
  7347. type: 'FeatureCollection',
  7348. features: jsons
  7349. };
  7350. }
  7351. });
  7352. // @namespace GeoJSON
  7353. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7354. // Creates a GeoJSON layer. Optionally accepts an object in
  7355. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7356. // (you can alternatively add it later with `addData` method) and an `options` object.
  7357. function geoJSON(geojson, options) {
  7358. return new GeoJSON(geojson, options);
  7359. }
  7360. // Backward compatibility.
  7361. var geoJson = geoJSON;
  7362. /*
  7363. * @class ImageOverlay
  7364. * @aka L.ImageOverlay
  7365. * @inherits Interactive layer
  7366. *
  7367. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7368. *
  7369. * @example
  7370. *
  7371. * ```js
  7372. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7373. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7374. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7375. * ```
  7376. */
  7377. var ImageOverlay = Layer.extend({
  7378. // @section
  7379. // @aka ImageOverlay options
  7380. options: {
  7381. // @option opacity: Number = 1.0
  7382. // The opacity of the image overlay.
  7383. opacity: 1,
  7384. // @option alt: String = ''
  7385. // Text for the `alt` attribute of the image (useful for accessibility).
  7386. alt: '',
  7387. // @option interactive: Boolean = false
  7388. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7389. interactive: false,
  7390. // @option crossOrigin: Boolean|String = false
  7391. // Whether the crossOrigin attribute will be added to the image.
  7392. // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.
  7393. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7394. crossOrigin: false,
  7395. // @option errorOverlayUrl: String = ''
  7396. // URL to the overlay image to show in place of the overlay that failed to load.
  7397. errorOverlayUrl: '',
  7398. // @option zIndex: Number = 1
  7399. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7400. zIndex: 1,
  7401. // @option className: String = ''
  7402. // A custom class name to assign to the image. Empty by default.
  7403. className: ''
  7404. },
  7405. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7406. this._url = url;
  7407. this._bounds = toLatLngBounds(bounds);
  7408. setOptions(this, options);
  7409. },
  7410. onAdd: function () {
  7411. if (!this._image) {
  7412. this._initImage();
  7413. if (this.options.opacity < 1) {
  7414. this._updateOpacity();
  7415. }
  7416. }
  7417. if (this.options.interactive) {
  7418. addClass(this._image, 'leaflet-interactive');
  7419. this.addInteractiveTarget(this._image);
  7420. }
  7421. this.getPane().appendChild(this._image);
  7422. this._reset();
  7423. },
  7424. onRemove: function () {
  7425. remove(this._image);
  7426. if (this.options.interactive) {
  7427. this.removeInteractiveTarget(this._image);
  7428. }
  7429. },
  7430. // @method setOpacity(opacity: Number): this
  7431. // Sets the opacity of the overlay.
  7432. setOpacity: function (opacity) {
  7433. this.options.opacity = opacity;
  7434. if (this._image) {
  7435. this._updateOpacity();
  7436. }
  7437. return this;
  7438. },
  7439. setStyle: function (styleOpts) {
  7440. if (styleOpts.opacity) {
  7441. this.setOpacity(styleOpts.opacity);
  7442. }
  7443. return this;
  7444. },
  7445. // @method bringToFront(): this
  7446. // Brings the layer to the top of all overlays.
  7447. bringToFront: function () {
  7448. if (this._map) {
  7449. toFront(this._image);
  7450. }
  7451. return this;
  7452. },
  7453. // @method bringToBack(): this
  7454. // Brings the layer to the bottom of all overlays.
  7455. bringToBack: function () {
  7456. if (this._map) {
  7457. toBack(this._image);
  7458. }
  7459. return this;
  7460. },
  7461. // @method setUrl(url: String): this
  7462. // Changes the URL of the image.
  7463. setUrl: function (url) {
  7464. this._url = url;
  7465. if (this._image) {
  7466. this._image.src = url;
  7467. }
  7468. return this;
  7469. },
  7470. // @method setBounds(bounds: LatLngBounds): this
  7471. // Update the bounds that this ImageOverlay covers
  7472. setBounds: function (bounds) {
  7473. this._bounds = toLatLngBounds(bounds);
  7474. if (this._map) {
  7475. this._reset();
  7476. }
  7477. return this;
  7478. },
  7479. getEvents: function () {
  7480. var events = {
  7481. zoom: this._reset,
  7482. viewreset: this._reset
  7483. };
  7484. if (this._zoomAnimated) {
  7485. events.zoomanim = this._animateZoom;
  7486. }
  7487. return events;
  7488. },
  7489. // @method setZIndex(value: Number): this
  7490. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7491. setZIndex: function (value) {
  7492. this.options.zIndex = value;
  7493. this._updateZIndex();
  7494. return this;
  7495. },
  7496. // @method getBounds(): LatLngBounds
  7497. // Get the bounds that this ImageOverlay covers
  7498. getBounds: function () {
  7499. return this._bounds;
  7500. },
  7501. // @method getElement(): HTMLElement
  7502. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7503. // used by this overlay.
  7504. getElement: function () {
  7505. return this._image;
  7506. },
  7507. _initImage: function () {
  7508. var wasElementSupplied = this._url.tagName === 'IMG';
  7509. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7510. addClass(img, 'leaflet-image-layer');
  7511. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7512. if (this.options.className) { addClass(img, this.options.className); }
  7513. img.onselectstart = falseFn;
  7514. img.onmousemove = falseFn;
  7515. // @event load: Event
  7516. // Fired when the ImageOverlay layer has loaded its image
  7517. img.onload = bind(this.fire, this, 'load');
  7518. img.onerror = bind(this._overlayOnError, this, 'error');
  7519. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7520. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7521. }
  7522. if (this.options.zIndex) {
  7523. this._updateZIndex();
  7524. }
  7525. if (wasElementSupplied) {
  7526. this._url = img.src;
  7527. return;
  7528. }
  7529. img.src = this._url;
  7530. img.alt = this.options.alt;
  7531. },
  7532. _animateZoom: function (e) {
  7533. var scale = this._map.getZoomScale(e.zoom),
  7534. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7535. setTransform(this._image, offset, scale);
  7536. },
  7537. _reset: function () {
  7538. var image = this._image,
  7539. bounds = new Bounds(
  7540. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7541. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7542. size = bounds.getSize();
  7543. setPosition(image, bounds.min);
  7544. image.style.width = size.x + 'px';
  7545. image.style.height = size.y + 'px';
  7546. },
  7547. _updateOpacity: function () {
  7548. setOpacity(this._image, this.options.opacity);
  7549. },
  7550. _updateZIndex: function () {
  7551. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7552. this._image.style.zIndex = this.options.zIndex;
  7553. }
  7554. },
  7555. _overlayOnError: function () {
  7556. // @event error: Event
  7557. // Fired when the ImageOverlay layer fails to load its image
  7558. this.fire('error');
  7559. var errorUrl = this.options.errorOverlayUrl;
  7560. if (errorUrl && this._url !== errorUrl) {
  7561. this._url = errorUrl;
  7562. this._image.src = errorUrl;
  7563. }
  7564. }
  7565. });
  7566. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7567. // Instantiates an image overlay object given the URL of the image and the
  7568. // geographical bounds it is tied to.
  7569. var imageOverlay = function (url, bounds, options) {
  7570. return new ImageOverlay(url, bounds, options);
  7571. };
  7572. /*
  7573. * @class VideoOverlay
  7574. * @aka L.VideoOverlay
  7575. * @inherits ImageOverlay
  7576. *
  7577. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7578. *
  7579. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7580. * HTML5 element.
  7581. *
  7582. * @example
  7583. *
  7584. * ```js
  7585. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7586. * videoBounds = [[ 32, -130], [ 13, -100]];
  7587. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7588. * ```
  7589. */
  7590. var VideoOverlay = ImageOverlay.extend({
  7591. // @section
  7592. // @aka VideoOverlay options
  7593. options: {
  7594. // @option autoplay: Boolean = true
  7595. // Whether the video starts playing automatically when loaded.
  7596. autoplay: true,
  7597. // @option loop: Boolean = true
  7598. // Whether the video will loop back to the beginning when played.
  7599. loop: true,
  7600. // @option keepAspectRatio: Boolean = true
  7601. // Whether the video will save aspect ratio after the projection.
  7602. // Relevant for supported browsers. Browser compatibility- https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
  7603. keepAspectRatio: true
  7604. },
  7605. _initImage: function () {
  7606. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7607. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7608. addClass(vid, 'leaflet-image-layer');
  7609. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7610. vid.onselectstart = falseFn;
  7611. vid.onmousemove = falseFn;
  7612. // @event load: Event
  7613. // Fired when the video has finished loading the first frame
  7614. vid.onloadeddata = bind(this.fire, this, 'load');
  7615. if (wasElementSupplied) {
  7616. var sourceElements = vid.getElementsByTagName('source');
  7617. var sources = [];
  7618. for (var j = 0; j < sourceElements.length; j++) {
  7619. sources.push(sourceElements[j].src);
  7620. }
  7621. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7622. return;
  7623. }
  7624. if (!isArray(this._url)) { this._url = [this._url]; }
  7625. if (!this.options.keepAspectRatio && vid.style.hasOwnProperty('objectFit')) { vid.style['objectFit'] = 'fill'; }
  7626. vid.autoplay = !!this.options.autoplay;
  7627. vid.loop = !!this.options.loop;
  7628. for (var i = 0; i < this._url.length; i++) {
  7629. var source = create$1('source');
  7630. source.src = this._url[i];
  7631. vid.appendChild(source);
  7632. }
  7633. }
  7634. // @method getElement(): HTMLVideoElement
  7635. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7636. // used by this overlay.
  7637. });
  7638. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7639. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7640. // geographical bounds it is tied to.
  7641. function videoOverlay(video, bounds, options) {
  7642. return new VideoOverlay(video, bounds, options);
  7643. }
  7644. /*
  7645. * @class SVGOverlay
  7646. * @aka L.SVGOverlay
  7647. * @inherits ImageOverlay
  7648. *
  7649. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7650. *
  7651. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7652. *
  7653. * @example
  7654. *
  7655. * ```js
  7656. * var element = '<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><image xlink:href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" height="200" width="200"/></svg>',
  7657. * elementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7658. * L.svgOverlay(element, elementBounds).addTo(map);
  7659. * ```
  7660. */
  7661. var SVGOverlay = ImageOverlay.extend({
  7662. _initImage: function () {
  7663. var el = this._image = this._url;
  7664. addClass(el, 'leaflet-image-layer');
  7665. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7666. el.onselectstart = falseFn;
  7667. el.onmousemove = falseFn;
  7668. }
  7669. // @method getElement(): SVGElement
  7670. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  7671. // used by this overlay.
  7672. });
  7673. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  7674. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  7675. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  7676. function svgOverlay(el, bounds, options) {
  7677. return new SVGOverlay(el, bounds, options);
  7678. }
  7679. /*
  7680. * @class DivOverlay
  7681. * @inherits Layer
  7682. * @aka L.DivOverlay
  7683. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7684. */
  7685. // @namespace DivOverlay
  7686. var DivOverlay = Layer.extend({
  7687. // @section
  7688. // @aka DivOverlay options
  7689. options: {
  7690. // @option offset: Point = Point(0, 7)
  7691. // The offset of the popup position. Useful to control the anchor
  7692. // of the popup when opening it on some overlays.
  7693. offset: [0, 7],
  7694. // @option className: String = ''
  7695. // A custom CSS class name to assign to the popup.
  7696. className: '',
  7697. // @option pane: String = 'popupPane'
  7698. // `Map pane` where the popup will be added.
  7699. pane: 'popupPane'
  7700. },
  7701. initialize: function (options, source) {
  7702. setOptions(this, options);
  7703. this._source = source;
  7704. },
  7705. onAdd: function (map) {
  7706. this._zoomAnimated = map._zoomAnimated;
  7707. if (!this._container) {
  7708. this._initLayout();
  7709. }
  7710. if (map._fadeAnimated) {
  7711. setOpacity(this._container, 0);
  7712. }
  7713. clearTimeout(this._removeTimeout);
  7714. this.getPane().appendChild(this._container);
  7715. this.update();
  7716. if (map._fadeAnimated) {
  7717. setOpacity(this._container, 1);
  7718. }
  7719. this.bringToFront();
  7720. },
  7721. onRemove: function (map) {
  7722. if (map._fadeAnimated) {
  7723. setOpacity(this._container, 0);
  7724. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7725. } else {
  7726. remove(this._container);
  7727. }
  7728. },
  7729. // @namespace Popup
  7730. // @method getLatLng: LatLng
  7731. // Returns the geographical point of popup.
  7732. getLatLng: function () {
  7733. return this._latlng;
  7734. },
  7735. // @method setLatLng(latlng: LatLng): this
  7736. // Sets the geographical point where the popup will open.
  7737. setLatLng: function (latlng) {
  7738. this._latlng = toLatLng(latlng);
  7739. if (this._map) {
  7740. this._updatePosition();
  7741. this._adjustPan();
  7742. }
  7743. return this;
  7744. },
  7745. // @method getContent: String|HTMLElement
  7746. // Returns the content of the popup.
  7747. getContent: function () {
  7748. return this._content;
  7749. },
  7750. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7751. // Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup.
  7752. setContent: function (content) {
  7753. this._content = content;
  7754. this.update();
  7755. return this;
  7756. },
  7757. // @method getElement: String|HTMLElement
  7758. // Alias for [getContent()](#popup-getcontent)
  7759. getElement: function () {
  7760. return this._container;
  7761. },
  7762. // @method update: null
  7763. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7764. update: function () {
  7765. if (!this._map) { return; }
  7766. this._container.style.visibility = 'hidden';
  7767. this._updateContent();
  7768. this._updateLayout();
  7769. this._updatePosition();
  7770. this._container.style.visibility = '';
  7771. this._adjustPan();
  7772. },
  7773. getEvents: function () {
  7774. var events = {
  7775. zoom: this._updatePosition,
  7776. viewreset: this._updatePosition
  7777. };
  7778. if (this._zoomAnimated) {
  7779. events.zoomanim = this._animateZoom;
  7780. }
  7781. return events;
  7782. },
  7783. // @method isOpen: Boolean
  7784. // Returns `true` when the popup is visible on the map.
  7785. isOpen: function () {
  7786. return !!this._map && this._map.hasLayer(this);
  7787. },
  7788. // @method bringToFront: this
  7789. // Brings this popup in front of other popups (in the same map pane).
  7790. bringToFront: function () {
  7791. if (this._map) {
  7792. toFront(this._container);
  7793. }
  7794. return this;
  7795. },
  7796. // @method bringToBack: this
  7797. // Brings this popup to the back of other popups (in the same map pane).
  7798. bringToBack: function () {
  7799. if (this._map) {
  7800. toBack(this._container);
  7801. }
  7802. return this;
  7803. },
  7804. _prepareOpen: function (parent, layer, latlng) {
  7805. if (!(layer instanceof Layer)) {
  7806. latlng = layer;
  7807. layer = parent;
  7808. }
  7809. if (layer instanceof FeatureGroup) {
  7810. for (var id in parent._layers) {
  7811. layer = parent._layers[id];
  7812. break;
  7813. }
  7814. }
  7815. if (!latlng) {
  7816. if (layer.getCenter) {
  7817. latlng = layer.getCenter();
  7818. } else if (layer.getLatLng) {
  7819. latlng = layer.getLatLng();
  7820. } else {
  7821. throw new Error('Unable to get source layer LatLng.');
  7822. }
  7823. }
  7824. // set overlay source to this layer
  7825. this._source = layer;
  7826. // update the overlay (content, layout, ect...)
  7827. this.update();
  7828. return latlng;
  7829. },
  7830. _updateContent: function () {
  7831. if (!this._content) { return; }
  7832. var node = this._contentNode;
  7833. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7834. if (typeof content === 'string') {
  7835. node.innerHTML = content;
  7836. } else {
  7837. while (node.hasChildNodes()) {
  7838. node.removeChild(node.firstChild);
  7839. }
  7840. node.appendChild(content);
  7841. }
  7842. this.fire('contentupdate');
  7843. },
  7844. _updatePosition: function () {
  7845. if (!this._map) { return; }
  7846. var pos = this._map.latLngToLayerPoint(this._latlng),
  7847. offset = toPoint(this.options.offset),
  7848. anchor = this._getAnchor();
  7849. if (this._zoomAnimated) {
  7850. setPosition(this._container, pos.add(anchor));
  7851. } else {
  7852. offset = offset.add(pos).add(anchor);
  7853. }
  7854. var bottom = this._containerBottom = -offset.y,
  7855. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7856. // bottom position the popup in case the height of the popup changes (images loading etc)
  7857. this._container.style.bottom = bottom + 'px';
  7858. this._container.style.left = left + 'px';
  7859. },
  7860. _getAnchor: function () {
  7861. return [0, 0];
  7862. }
  7863. });
  7864. /*
  7865. * @class Popup
  7866. * @inherits DivOverlay
  7867. * @aka L.Popup
  7868. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7869. * open popups while making sure that only one popup is open at one time
  7870. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7871. *
  7872. * @example
  7873. *
  7874. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7875. *
  7876. * ```js
  7877. * marker.bindPopup(popupContent).openPopup();
  7878. * ```
  7879. * Path overlays like polylines also have a `bindPopup` method.
  7880. * Here's a more complicated way to open a popup on a map:
  7881. *
  7882. * ```js
  7883. * var popup = L.popup()
  7884. * .setLatLng(latlng)
  7885. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7886. * .openOn(map);
  7887. * ```
  7888. */
  7889. // @namespace Popup
  7890. var Popup = DivOverlay.extend({
  7891. // @section
  7892. // @aka Popup options
  7893. options: {
  7894. // @option maxWidth: Number = 300
  7895. // Max width of the popup, in pixels.
  7896. maxWidth: 300,
  7897. // @option minWidth: Number = 50
  7898. // Min width of the popup, in pixels.
  7899. minWidth: 50,
  7900. // @option maxHeight: Number = null
  7901. // If set, creates a scrollable container of the given height
  7902. // inside a popup if its content exceeds it.
  7903. maxHeight: null,
  7904. // @option autoPan: Boolean = true
  7905. // Set it to `false` if you don't want the map to do panning animation
  7906. // to fit the opened popup.
  7907. autoPan: true,
  7908. // @option autoPanPaddingTopLeft: Point = null
  7909. // The margin between the popup and the top left corner of the map
  7910. // view after autopanning was performed.
  7911. autoPanPaddingTopLeft: null,
  7912. // @option autoPanPaddingBottomRight: Point = null
  7913. // The margin between the popup and the bottom right corner of the map
  7914. // view after autopanning was performed.
  7915. autoPanPaddingBottomRight: null,
  7916. // @option autoPanPadding: Point = Point(5, 5)
  7917. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7918. autoPanPadding: [5, 5],
  7919. // @option keepInView: Boolean = false
  7920. // Set it to `true` if you want to prevent users from panning the popup
  7921. // off of the screen while it is open.
  7922. keepInView: false,
  7923. // @option closeButton: Boolean = true
  7924. // Controls the presence of a close button in the popup.
  7925. closeButton: true,
  7926. // @option autoClose: Boolean = true
  7927. // Set it to `false` if you want to override the default behavior of
  7928. // the popup closing when another popup is opened.
  7929. autoClose: true,
  7930. // @option closeOnEscapeKey: Boolean = true
  7931. // Set it to `false` if you want to override the default behavior of
  7932. // the ESC key for closing of the popup.
  7933. closeOnEscapeKey: true,
  7934. // @option closeOnClick: Boolean = *
  7935. // Set it if you want to override the default behavior of the popup closing when user clicks
  7936. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7937. // @option className: String = ''
  7938. // A custom CSS class name to assign to the popup.
  7939. className: ''
  7940. },
  7941. // @namespace Popup
  7942. // @method openOn(map: Map): this
  7943. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7944. openOn: function (map) {
  7945. map.openPopup(this);
  7946. return this;
  7947. },
  7948. onAdd: function (map) {
  7949. DivOverlay.prototype.onAdd.call(this, map);
  7950. // @namespace Map
  7951. // @section Popup events
  7952. // @event popupopen: PopupEvent
  7953. // Fired when a popup is opened in the map
  7954. map.fire('popupopen', {popup: this});
  7955. if (this._source) {
  7956. // @namespace Layer
  7957. // @section Popup events
  7958. // @event popupopen: PopupEvent
  7959. // Fired when a popup bound to this layer is opened
  7960. this._source.fire('popupopen', {popup: this}, true);
  7961. // For non-path layers, we toggle the popup when clicking
  7962. // again the layer, so prevent the map to reopen it.
  7963. if (!(this._source instanceof Path)) {
  7964. this._source.on('preclick', stopPropagation);
  7965. }
  7966. }
  7967. },
  7968. onRemove: function (map) {
  7969. DivOverlay.prototype.onRemove.call(this, map);
  7970. // @namespace Map
  7971. // @section Popup events
  7972. // @event popupclose: PopupEvent
  7973. // Fired when a popup in the map is closed
  7974. map.fire('popupclose', {popup: this});
  7975. if (this._source) {
  7976. // @namespace Layer
  7977. // @section Popup events
  7978. // @event popupclose: PopupEvent
  7979. // Fired when a popup bound to this layer is closed
  7980. this._source.fire('popupclose', {popup: this}, true);
  7981. if (!(this._source instanceof Path)) {
  7982. this._source.off('preclick', stopPropagation);
  7983. }
  7984. }
  7985. },
  7986. getEvents: function () {
  7987. var events = DivOverlay.prototype.getEvents.call(this);
  7988. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  7989. events.preclick = this._close;
  7990. }
  7991. if (this.options.keepInView) {
  7992. events.moveend = this._adjustPan;
  7993. }
  7994. return events;
  7995. },
  7996. _close: function () {
  7997. if (this._map) {
  7998. this._map.closePopup(this);
  7999. }
  8000. },
  8001. _initLayout: function () {
  8002. var prefix = 'leaflet-popup',
  8003. container = this._container = create$1('div',
  8004. prefix + ' ' + (this.options.className || '') +
  8005. ' leaflet-zoom-animated');
  8006. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8007. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8008. disableClickPropagation(wrapper);
  8009. disableScrollPropagation(this._contentNode);
  8010. on(wrapper, 'contextmenu', stopPropagation);
  8011. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8012. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8013. if (this.options.closeButton) {
  8014. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8015. closeButton.href = '#close';
  8016. closeButton.innerHTML = '&#215;';
  8017. on(closeButton, 'click', this._onCloseButtonClick, this);
  8018. }
  8019. },
  8020. _updateLayout: function () {
  8021. var container = this._contentNode,
  8022. style = container.style;
  8023. style.width = '';
  8024. style.whiteSpace = 'nowrap';
  8025. var width = container.offsetWidth;
  8026. width = Math.min(width, this.options.maxWidth);
  8027. width = Math.max(width, this.options.minWidth);
  8028. style.width = (width + 1) + 'px';
  8029. style.whiteSpace = '';
  8030. style.height = '';
  8031. var height = container.offsetHeight,
  8032. maxHeight = this.options.maxHeight,
  8033. scrolledClass = 'leaflet-popup-scrolled';
  8034. if (maxHeight && height > maxHeight) {
  8035. style.height = maxHeight + 'px';
  8036. addClass(container, scrolledClass);
  8037. } else {
  8038. removeClass(container, scrolledClass);
  8039. }
  8040. this._containerWidth = this._container.offsetWidth;
  8041. },
  8042. _animateZoom: function (e) {
  8043. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8044. anchor = this._getAnchor();
  8045. setPosition(this._container, pos.add(anchor));
  8046. },
  8047. _adjustPan: function () {
  8048. if (!this.options.autoPan) { return; }
  8049. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8050. var map = this._map,
  8051. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8052. containerHeight = this._container.offsetHeight + marginBottom,
  8053. containerWidth = this._containerWidth,
  8054. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8055. layerPos._add(getPosition(this._container));
  8056. var containerPos = map.layerPointToContainerPoint(layerPos),
  8057. padding = toPoint(this.options.autoPanPadding),
  8058. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8059. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8060. size = map.getSize(),
  8061. dx = 0,
  8062. dy = 0;
  8063. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8064. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8065. }
  8066. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8067. dx = containerPos.x - paddingTL.x;
  8068. }
  8069. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8070. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8071. }
  8072. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8073. dy = containerPos.y - paddingTL.y;
  8074. }
  8075. // @namespace Map
  8076. // @section Popup events
  8077. // @event autopanstart: Event
  8078. // Fired when the map starts autopanning when opening a popup.
  8079. if (dx || dy) {
  8080. map
  8081. .fire('autopanstart')
  8082. .panBy([dx, dy]);
  8083. }
  8084. },
  8085. _onCloseButtonClick: function (e) {
  8086. this._close();
  8087. stop(e);
  8088. },
  8089. _getAnchor: function () {
  8090. // Where should we anchor the popup on the source layer?
  8091. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8092. }
  8093. });
  8094. // @namespace Popup
  8095. // @factory L.popup(options?: Popup options, source?: Layer)
  8096. // Instantiates a `Popup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers.
  8097. var popup = function (options, source) {
  8098. return new Popup(options, source);
  8099. };
  8100. /* @namespace Map
  8101. * @section Interaction Options
  8102. * @option closePopupOnClick: Boolean = true
  8103. * Set it to `false` if you don't want popups to close when user clicks the map.
  8104. */
  8105. Map.mergeOptions({
  8106. closePopupOnClick: true
  8107. });
  8108. // @namespace Map
  8109. // @section Methods for Layers and Controls
  8110. Map.include({
  8111. // @method openPopup(popup: Popup): this
  8112. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8113. // @alternative
  8114. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8115. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8116. openPopup: function (popup, latlng, options) {
  8117. if (!(popup instanceof Popup)) {
  8118. popup = new Popup(options).setContent(popup);
  8119. }
  8120. if (latlng) {
  8121. popup.setLatLng(latlng);
  8122. }
  8123. if (this.hasLayer(popup)) {
  8124. return this;
  8125. }
  8126. if (this._popup && this._popup.options.autoClose) {
  8127. this.closePopup();
  8128. }
  8129. this._popup = popup;
  8130. return this.addLayer(popup);
  8131. },
  8132. // @method closePopup(popup?: Popup): this
  8133. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8134. closePopup: function (popup) {
  8135. if (!popup || popup === this._popup) {
  8136. popup = this._popup;
  8137. this._popup = null;
  8138. }
  8139. if (popup) {
  8140. this.removeLayer(popup);
  8141. }
  8142. return this;
  8143. }
  8144. });
  8145. /*
  8146. * @namespace Layer
  8147. * @section Popup methods example
  8148. *
  8149. * All layers share a set of methods convenient for binding popups to it.
  8150. *
  8151. * ```js
  8152. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8153. * layer.openPopup();
  8154. * layer.closePopup();
  8155. * ```
  8156. *
  8157. * Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened.
  8158. */
  8159. // @section Popup methods
  8160. Layer.include({
  8161. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8162. // Binds a popup to the layer with the passed `content` and sets up the
  8163. // necessary event listeners. If a `Function` is passed it will receive
  8164. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8165. bindPopup: function (content, options) {
  8166. if (content instanceof Popup) {
  8167. setOptions(content, options);
  8168. this._popup = content;
  8169. content._source = this;
  8170. } else {
  8171. if (!this._popup || options) {
  8172. this._popup = new Popup(options, this);
  8173. }
  8174. this._popup.setContent(content);
  8175. }
  8176. if (!this._popupHandlersAdded) {
  8177. this.on({
  8178. click: this._openPopup,
  8179. keypress: this._onKeyPress,
  8180. remove: this.closePopup,
  8181. move: this._movePopup
  8182. });
  8183. this._popupHandlersAdded = true;
  8184. }
  8185. return this;
  8186. },
  8187. // @method unbindPopup(): this
  8188. // Removes the popup previously bound with `bindPopup`.
  8189. unbindPopup: function () {
  8190. if (this._popup) {
  8191. this.off({
  8192. click: this._openPopup,
  8193. keypress: this._onKeyPress,
  8194. remove: this.closePopup,
  8195. move: this._movePopup
  8196. });
  8197. this._popupHandlersAdded = false;
  8198. this._popup = null;
  8199. }
  8200. return this;
  8201. },
  8202. // @method openPopup(latlng?: LatLng): this
  8203. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8204. openPopup: function (layer, latlng) {
  8205. if (this._popup && this._map) {
  8206. latlng = this._popup._prepareOpen(this, layer, latlng);
  8207. // open the popup on the map
  8208. this._map.openPopup(this._popup, latlng);
  8209. }
  8210. return this;
  8211. },
  8212. // @method closePopup(): this
  8213. // Closes the popup bound to this layer if it is open.
  8214. closePopup: function () {
  8215. if (this._popup) {
  8216. this._popup._close();
  8217. }
  8218. return this;
  8219. },
  8220. // @method togglePopup(): this
  8221. // Opens or closes the popup bound to this layer depending on its current state.
  8222. togglePopup: function (target) {
  8223. if (this._popup) {
  8224. if (this._popup._map) {
  8225. this.closePopup();
  8226. } else {
  8227. this.openPopup(target);
  8228. }
  8229. }
  8230. return this;
  8231. },
  8232. // @method isPopupOpen(): boolean
  8233. // Returns `true` if the popup bound to this layer is currently open.
  8234. isPopupOpen: function () {
  8235. return (this._popup ? this._popup.isOpen() : false);
  8236. },
  8237. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8238. // Sets the content of the popup bound to this layer.
  8239. setPopupContent: function (content) {
  8240. if (this._popup) {
  8241. this._popup.setContent(content);
  8242. }
  8243. return this;
  8244. },
  8245. // @method getPopup(): Popup
  8246. // Returns the popup bound to this layer.
  8247. getPopup: function () {
  8248. return this._popup;
  8249. },
  8250. _openPopup: function (e) {
  8251. var layer = e.layer || e.target;
  8252. if (!this._popup) {
  8253. return;
  8254. }
  8255. if (!this._map) {
  8256. return;
  8257. }
  8258. // prevent map click
  8259. stop(e);
  8260. // if this inherits from Path its a vector and we can just
  8261. // open the popup at the new location
  8262. if (layer instanceof Path) {
  8263. this.openPopup(e.layer || e.target, e.latlng);
  8264. return;
  8265. }
  8266. // otherwise treat it like a marker and figure out
  8267. // if we should toggle it open/closed
  8268. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  8269. this.closePopup();
  8270. } else {
  8271. this.openPopup(layer, e.latlng);
  8272. }
  8273. },
  8274. _movePopup: function (e) {
  8275. this._popup.setLatLng(e.latlng);
  8276. },
  8277. _onKeyPress: function (e) {
  8278. if (e.originalEvent.keyCode === 13) {
  8279. this._openPopup(e);
  8280. }
  8281. }
  8282. });
  8283. /*
  8284. * @class Tooltip
  8285. * @inherits DivOverlay
  8286. * @aka L.Tooltip
  8287. * Used to display small texts on top of map layers.
  8288. *
  8289. * @example
  8290. *
  8291. * ```js
  8292. * marker.bindTooltip("my tooltip text").openTooltip();
  8293. * ```
  8294. * Note about tooltip offset. Leaflet takes two options in consideration
  8295. * for computing tooltip offsetting:
  8296. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8297. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8298. * move it to the bottom. Negatives will move to the left and top.
  8299. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8300. * should adapt this value if you use a custom icon.
  8301. */
  8302. // @namespace Tooltip
  8303. var Tooltip = DivOverlay.extend({
  8304. // @section
  8305. // @aka Tooltip options
  8306. options: {
  8307. // @option pane: String = 'tooltipPane'
  8308. // `Map pane` where the tooltip will be added.
  8309. pane: 'tooltipPane',
  8310. // @option offset: Point = Point(0, 0)
  8311. // Optional offset of the tooltip position.
  8312. offset: [0, 0],
  8313. // @option direction: String = 'auto'
  8314. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8315. // `top`, `bottom`, `center`, `auto`.
  8316. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8317. // position on the map.
  8318. direction: 'auto',
  8319. // @option permanent: Boolean = false
  8320. // Whether to open the tooltip permanently or only on mouseover.
  8321. permanent: false,
  8322. // @option sticky: Boolean = false
  8323. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8324. sticky: false,
  8325. // @option interactive: Boolean = false
  8326. // If true, the tooltip will listen to the feature events.
  8327. interactive: false,
  8328. // @option opacity: Number = 0.9
  8329. // Tooltip container opacity.
  8330. opacity: 0.9
  8331. },
  8332. onAdd: function (map) {
  8333. DivOverlay.prototype.onAdd.call(this, map);
  8334. this.setOpacity(this.options.opacity);
  8335. // @namespace Map
  8336. // @section Tooltip events
  8337. // @event tooltipopen: TooltipEvent
  8338. // Fired when a tooltip is opened in the map.
  8339. map.fire('tooltipopen', {tooltip: this});
  8340. if (this._source) {
  8341. // @namespace Layer
  8342. // @section Tooltip events
  8343. // @event tooltipopen: TooltipEvent
  8344. // Fired when a tooltip bound to this layer is opened.
  8345. this._source.fire('tooltipopen', {tooltip: this}, true);
  8346. }
  8347. },
  8348. onRemove: function (map) {
  8349. DivOverlay.prototype.onRemove.call(this, map);
  8350. // @namespace Map
  8351. // @section Tooltip events
  8352. // @event tooltipclose: TooltipEvent
  8353. // Fired when a tooltip in the map is closed.
  8354. map.fire('tooltipclose', {tooltip: this});
  8355. if (this._source) {
  8356. // @namespace Layer
  8357. // @section Tooltip events
  8358. // @event tooltipclose: TooltipEvent
  8359. // Fired when a tooltip bound to this layer is closed.
  8360. this._source.fire('tooltipclose', {tooltip: this}, true);
  8361. }
  8362. },
  8363. getEvents: function () {
  8364. var events = DivOverlay.prototype.getEvents.call(this);
  8365. if (touch && !this.options.permanent) {
  8366. events.preclick = this._close;
  8367. }
  8368. return events;
  8369. },
  8370. _close: function () {
  8371. if (this._map) {
  8372. this._map.closeTooltip(this);
  8373. }
  8374. },
  8375. _initLayout: function () {
  8376. var prefix = 'leaflet-tooltip',
  8377. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8378. this._contentNode = this._container = create$1('div', className);
  8379. },
  8380. _updateLayout: function () {},
  8381. _adjustPan: function () {},
  8382. _setPosition: function (pos) {
  8383. var map = this._map,
  8384. container = this._container,
  8385. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8386. tooltipPoint = map.layerPointToContainerPoint(pos),
  8387. direction = this.options.direction,
  8388. tooltipWidth = container.offsetWidth,
  8389. tooltipHeight = container.offsetHeight,
  8390. offset = toPoint(this.options.offset),
  8391. anchor = this._getAnchor();
  8392. if (direction === 'top') {
  8393. pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  8394. } else if (direction === 'bottom') {
  8395. pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
  8396. } else if (direction === 'center') {
  8397. pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  8398. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  8399. direction = 'right';
  8400. pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  8401. } else {
  8402. direction = 'left';
  8403. pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  8404. }
  8405. removeClass(container, 'leaflet-tooltip-right');
  8406. removeClass(container, 'leaflet-tooltip-left');
  8407. removeClass(container, 'leaflet-tooltip-top');
  8408. removeClass(container, 'leaflet-tooltip-bottom');
  8409. addClass(container, 'leaflet-tooltip-' + direction);
  8410. setPosition(container, pos);
  8411. },
  8412. _updatePosition: function () {
  8413. var pos = this._map.latLngToLayerPoint(this._latlng);
  8414. this._setPosition(pos);
  8415. },
  8416. setOpacity: function (opacity) {
  8417. this.options.opacity = opacity;
  8418. if (this._container) {
  8419. setOpacity(this._container, opacity);
  8420. }
  8421. },
  8422. _animateZoom: function (e) {
  8423. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8424. this._setPosition(pos);
  8425. },
  8426. _getAnchor: function () {
  8427. // Where should we anchor the tooltip on the source layer?
  8428. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8429. }
  8430. });
  8431. // @namespace Tooltip
  8432. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8433. // Instantiates a Tooltip object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the tooltip with a reference to the Layer to which it refers.
  8434. var tooltip = function (options, source) {
  8435. return new Tooltip(options, source);
  8436. };
  8437. // @namespace Map
  8438. // @section Methods for Layers and Controls
  8439. Map.include({
  8440. // @method openTooltip(tooltip: Tooltip): this
  8441. // Opens the specified tooltip.
  8442. // @alternative
  8443. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8444. // Creates a tooltip with the specified content and options and open it.
  8445. openTooltip: function (tooltip, latlng, options) {
  8446. if (!(tooltip instanceof Tooltip)) {
  8447. tooltip = new Tooltip(options).setContent(tooltip);
  8448. }
  8449. if (latlng) {
  8450. tooltip.setLatLng(latlng);
  8451. }
  8452. if (this.hasLayer(tooltip)) {
  8453. return this;
  8454. }
  8455. return this.addLayer(tooltip);
  8456. },
  8457. // @method closeTooltip(tooltip?: Tooltip): this
  8458. // Closes the tooltip given as parameter.
  8459. closeTooltip: function (tooltip) {
  8460. if (tooltip) {
  8461. this.removeLayer(tooltip);
  8462. }
  8463. return this;
  8464. }
  8465. });
  8466. /*
  8467. * @namespace Layer
  8468. * @section Tooltip methods example
  8469. *
  8470. * All layers share a set of methods convenient for binding tooltips to it.
  8471. *
  8472. * ```js
  8473. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8474. * layer.openTooltip();
  8475. * layer.closeTooltip();
  8476. * ```
  8477. */
  8478. // @section Tooltip methods
  8479. Layer.include({
  8480. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8481. // Binds a tooltip to the layer with the passed `content` and sets up the
  8482. // necessary event listeners. If a `Function` is passed it will receive
  8483. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8484. bindTooltip: function (content, options) {
  8485. if (content instanceof Tooltip) {
  8486. setOptions(content, options);
  8487. this._tooltip = content;
  8488. content._source = this;
  8489. } else {
  8490. if (!this._tooltip || options) {
  8491. this._tooltip = new Tooltip(options, this);
  8492. }
  8493. this._tooltip.setContent(content);
  8494. }
  8495. this._initTooltipInteractions();
  8496. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8497. this.openTooltip();
  8498. }
  8499. return this;
  8500. },
  8501. // @method unbindTooltip(): this
  8502. // Removes the tooltip previously bound with `bindTooltip`.
  8503. unbindTooltip: function () {
  8504. if (this._tooltip) {
  8505. this._initTooltipInteractions(true);
  8506. this.closeTooltip();
  8507. this._tooltip = null;
  8508. }
  8509. return this;
  8510. },
  8511. _initTooltipInteractions: function (remove$$1) {
  8512. if (!remove$$1 && this._tooltipHandlersAdded) { return; }
  8513. var onOff = remove$$1 ? 'off' : 'on',
  8514. events = {
  8515. remove: this.closeTooltip,
  8516. move: this._moveTooltip
  8517. };
  8518. if (!this._tooltip.options.permanent) {
  8519. events.mouseover = this._openTooltip;
  8520. events.mouseout = this.closeTooltip;
  8521. if (this._tooltip.options.sticky) {
  8522. events.mousemove = this._moveTooltip;
  8523. }
  8524. if (touch) {
  8525. events.click = this._openTooltip;
  8526. }
  8527. } else {
  8528. events.add = this._openTooltip;
  8529. }
  8530. this[onOff](events);
  8531. this._tooltipHandlersAdded = !remove$$1;
  8532. },
  8533. // @method openTooltip(latlng?: LatLng): this
  8534. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8535. openTooltip: function (layer, latlng) {
  8536. if (this._tooltip && this._map) {
  8537. latlng = this._tooltip._prepareOpen(this, layer, latlng);
  8538. // open the tooltip on the map
  8539. this._map.openTooltip(this._tooltip, latlng);
  8540. // Tooltip container may not be defined if not permanent and never
  8541. // opened.
  8542. if (this._tooltip.options.interactive && this._tooltip._container) {
  8543. addClass(this._tooltip._container, 'leaflet-clickable');
  8544. this.addInteractiveTarget(this._tooltip._container);
  8545. }
  8546. }
  8547. return this;
  8548. },
  8549. // @method closeTooltip(): this
  8550. // Closes the tooltip bound to this layer if it is open.
  8551. closeTooltip: function () {
  8552. if (this._tooltip) {
  8553. this._tooltip._close();
  8554. if (this._tooltip.options.interactive && this._tooltip._container) {
  8555. removeClass(this._tooltip._container, 'leaflet-clickable');
  8556. this.removeInteractiveTarget(this._tooltip._container);
  8557. }
  8558. }
  8559. return this;
  8560. },
  8561. // @method toggleTooltip(): this
  8562. // Opens or closes the tooltip bound to this layer depending on its current state.
  8563. toggleTooltip: function (target) {
  8564. if (this._tooltip) {
  8565. if (this._tooltip._map) {
  8566. this.closeTooltip();
  8567. } else {
  8568. this.openTooltip(target);
  8569. }
  8570. }
  8571. return this;
  8572. },
  8573. // @method isTooltipOpen(): boolean
  8574. // Returns `true` if the tooltip bound to this layer is currently open.
  8575. isTooltipOpen: function () {
  8576. return this._tooltip.isOpen();
  8577. },
  8578. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8579. // Sets the content of the tooltip bound to this layer.
  8580. setTooltipContent: function (content) {
  8581. if (this._tooltip) {
  8582. this._tooltip.setContent(content);
  8583. }
  8584. return this;
  8585. },
  8586. // @method getTooltip(): Tooltip
  8587. // Returns the tooltip bound to this layer.
  8588. getTooltip: function () {
  8589. return this._tooltip;
  8590. },
  8591. _openTooltip: function (e) {
  8592. var layer = e.layer || e.target;
  8593. if (!this._tooltip || !this._map) {
  8594. return;
  8595. }
  8596. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8597. },
  8598. _moveTooltip: function (e) {
  8599. var latlng = e.latlng, containerPoint, layerPoint;
  8600. if (this._tooltip.options.sticky && e.originalEvent) {
  8601. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8602. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8603. latlng = this._map.layerPointToLatLng(layerPoint);
  8604. }
  8605. this._tooltip.setLatLng(latlng);
  8606. }
  8607. });
  8608. /*
  8609. * @class DivIcon
  8610. * @aka L.DivIcon
  8611. * @inherits Icon
  8612. *
  8613. * Represents a lightweight icon for markers that uses a simple `<div>`
  8614. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8615. *
  8616. * @example
  8617. * ```js
  8618. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8619. * // you can set .my-div-icon styles in CSS
  8620. *
  8621. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8622. * ```
  8623. *
  8624. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8625. */
  8626. var DivIcon = Icon.extend({
  8627. options: {
  8628. // @section
  8629. // @aka DivIcon options
  8630. iconSize: [12, 12], // also can be set through CSS
  8631. // iconAnchor: (Point),
  8632. // popupAnchor: (Point),
  8633. // @option html: String|HTMLElement = ''
  8634. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  8635. // an instance of `HTMLElement`.
  8636. html: false,
  8637. // @option bgPos: Point = [0, 0]
  8638. // Optional relative position of the background, in pixels
  8639. bgPos: null,
  8640. className: 'leaflet-div-icon'
  8641. },
  8642. createIcon: function (oldIcon) {
  8643. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8644. options = this.options;
  8645. if (options.html instanceof Element) {
  8646. empty(div);
  8647. div.appendChild(options.html);
  8648. } else {
  8649. div.innerHTML = options.html !== false ? options.html : '';
  8650. }
  8651. if (options.bgPos) {
  8652. var bgPos = toPoint(options.bgPos);
  8653. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8654. }
  8655. this._setIconStyles(div, 'icon');
  8656. return div;
  8657. },
  8658. createShadow: function () {
  8659. return null;
  8660. }
  8661. });
  8662. // @factory L.divIcon(options: DivIcon options)
  8663. // Creates a `DivIcon` instance with the given options.
  8664. function divIcon(options) {
  8665. return new DivIcon(options);
  8666. }
  8667. Icon.Default = IconDefault;
  8668. /*
  8669. * @class GridLayer
  8670. * @inherits Layer
  8671. * @aka L.GridLayer
  8672. *
  8673. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8674. * GridLayer can be extended to create a tiled grid of HTML elements like `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you.
  8675. *
  8676. *
  8677. * @section Synchronous usage
  8678. * @example
  8679. *
  8680. * To create a custom layer, extend GridLayer and implement the `createTile()` method, which will be passed a `Point` object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile.
  8681. *
  8682. * ```js
  8683. * var CanvasLayer = L.GridLayer.extend({
  8684. * createTile: function(coords){
  8685. * // create a <canvas> element for drawing
  8686. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8687. *
  8688. * // setup tile width and height according to the options
  8689. * var size = this.getTileSize();
  8690. * tile.width = size.x;
  8691. * tile.height = size.y;
  8692. *
  8693. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8694. * var ctx = tile.getContext('2d');
  8695. *
  8696. * // return the tile so it can be rendered on screen
  8697. * return tile;
  8698. * }
  8699. * });
  8700. * ```
  8701. *
  8702. * @section Asynchronous usage
  8703. * @example
  8704. *
  8705. * Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback.
  8706. *
  8707. * ```js
  8708. * var CanvasLayer = L.GridLayer.extend({
  8709. * createTile: function(coords, done){
  8710. * var error;
  8711. *
  8712. * // create a <canvas> element for drawing
  8713. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8714. *
  8715. * // setup tile width and height according to the options
  8716. * var size = this.getTileSize();
  8717. * tile.width = size.x;
  8718. * tile.height = size.y;
  8719. *
  8720. * // draw something asynchronously and pass the tile to the done() callback
  8721. * setTimeout(function() {
  8722. * done(error, tile);
  8723. * }, 1000);
  8724. *
  8725. * return tile;
  8726. * }
  8727. * });
  8728. * ```
  8729. *
  8730. * @section
  8731. */
  8732. var GridLayer = Layer.extend({
  8733. // @section
  8734. // @aka GridLayer options
  8735. options: {
  8736. // @option tileSize: Number|Point = 256
  8737. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8738. tileSize: 256,
  8739. // @option opacity: Number = 1.0
  8740. // Opacity of the tiles. Can be used in the `createTile()` function.
  8741. opacity: 1,
  8742. // @option updateWhenIdle: Boolean = (depends)
  8743. // Load new tiles only when panning ends.
  8744. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8745. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8746. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8747. updateWhenIdle: mobile,
  8748. // @option updateWhenZooming: Boolean = true
  8749. // By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.
  8750. updateWhenZooming: true,
  8751. // @option updateInterval: Number = 200
  8752. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8753. updateInterval: 200,
  8754. // @option zIndex: Number = 1
  8755. // The explicit zIndex of the tile layer.
  8756. zIndex: 1,
  8757. // @option bounds: LatLngBounds = undefined
  8758. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8759. bounds: null,
  8760. // @option minZoom: Number = 0
  8761. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8762. minZoom: 0,
  8763. // @option maxZoom: Number = undefined
  8764. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8765. maxZoom: undefined,
  8766. // @option maxNativeZoom: Number = undefined
  8767. // Maximum zoom number the tile source has available. If it is specified,
  8768. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8769. // from `maxNativeZoom` level and auto-scaled.
  8770. maxNativeZoom: undefined,
  8771. // @option minNativeZoom: Number = undefined
  8772. // Minimum zoom number the tile source has available. If it is specified,
  8773. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8774. // from `minNativeZoom` level and auto-scaled.
  8775. minNativeZoom: undefined,
  8776. // @option noWrap: Boolean = false
  8777. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8778. // GridLayer will only be displayed once at low zoom levels. Has no
  8779. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8780. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8781. // tiles outside the CRS limits.
  8782. noWrap: false,
  8783. // @option pane: String = 'tilePane'
  8784. // `Map pane` where the grid layer will be added.
  8785. pane: 'tilePane',
  8786. // @option className: String = ''
  8787. // A custom class name to assign to the tile layer. Empty by default.
  8788. className: '',
  8789. // @option keepBuffer: Number = 2
  8790. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8791. keepBuffer: 2
  8792. },
  8793. initialize: function (options) {
  8794. setOptions(this, options);
  8795. },
  8796. onAdd: function () {
  8797. this._initContainer();
  8798. this._levels = {};
  8799. this._tiles = {};
  8800. this._resetView();
  8801. this._update();
  8802. },
  8803. beforeAdd: function (map) {
  8804. map._addZoomLimit(this);
  8805. },
  8806. onRemove: function (map) {
  8807. this._removeAllTiles();
  8808. remove(this._container);
  8809. map._removeZoomLimit(this);
  8810. this._container = null;
  8811. this._tileZoom = undefined;
  8812. },
  8813. // @method bringToFront: this
  8814. // Brings the tile layer to the top of all tile layers.
  8815. bringToFront: function () {
  8816. if (this._map) {
  8817. toFront(this._container);
  8818. this._setAutoZIndex(Math.max);
  8819. }
  8820. return this;
  8821. },
  8822. // @method bringToBack: this
  8823. // Brings the tile layer to the bottom of all tile layers.
  8824. bringToBack: function () {
  8825. if (this._map) {
  8826. toBack(this._container);
  8827. this._setAutoZIndex(Math.min);
  8828. }
  8829. return this;
  8830. },
  8831. // @method getContainer: HTMLElement
  8832. // Returns the HTML element that contains the tiles for this layer.
  8833. getContainer: function () {
  8834. return this._container;
  8835. },
  8836. // @method setOpacity(opacity: Number): this
  8837. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8838. setOpacity: function (opacity) {
  8839. this.options.opacity = opacity;
  8840. this._updateOpacity();
  8841. return this;
  8842. },
  8843. // @method setZIndex(zIndex: Number): this
  8844. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8845. setZIndex: function (zIndex) {
  8846. this.options.zIndex = zIndex;
  8847. this._updateZIndex();
  8848. return this;
  8849. },
  8850. // @method isLoading: Boolean
  8851. // Returns `true` if any tile in the grid layer has not finished loading.
  8852. isLoading: function () {
  8853. return this._loading;
  8854. },
  8855. // @method redraw: this
  8856. // Causes the layer to clear all the tiles and request them again.
  8857. redraw: function () {
  8858. if (this._map) {
  8859. this._removeAllTiles();
  8860. this._update();
  8861. }
  8862. return this;
  8863. },
  8864. getEvents: function () {
  8865. var events = {
  8866. viewprereset: this._invalidateAll,
  8867. viewreset: this._resetView,
  8868. zoom: this._resetView,
  8869. moveend: this._onMoveEnd
  8870. };
  8871. if (!this.options.updateWhenIdle) {
  8872. // update tiles on move, but not more often than once per given interval
  8873. if (!this._onMove) {
  8874. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8875. }
  8876. events.move = this._onMove;
  8877. }
  8878. if (this._zoomAnimated) {
  8879. events.zoomanim = this._animateZoom;
  8880. }
  8881. return events;
  8882. },
  8883. // @section Extension methods
  8884. // Layers extending `GridLayer` shall reimplement the following method.
  8885. // @method createTile(coords: Object, done?: Function): HTMLElement
  8886. // Called only internally, must be overridden by classes extending `GridLayer`.
  8887. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8888. // is specified, it must be called when the tile has finished loading and drawing.
  8889. createTile: function () {
  8890. return document.createElement('div');
  8891. },
  8892. // @section
  8893. // @method getTileSize: Point
  8894. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8895. getTileSize: function () {
  8896. var s = this.options.tileSize;
  8897. return s instanceof Point ? s : new Point(s, s);
  8898. },
  8899. _updateZIndex: function () {
  8900. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8901. this._container.style.zIndex = this.options.zIndex;
  8902. }
  8903. },
  8904. _setAutoZIndex: function (compare) {
  8905. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8906. var layers = this.getPane().children,
  8907. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8908. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8909. zIndex = layers[i].style.zIndex;
  8910. if (layers[i] !== this._container && zIndex) {
  8911. edgeZIndex = compare(edgeZIndex, +zIndex);
  8912. }
  8913. }
  8914. if (isFinite(edgeZIndex)) {
  8915. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8916. this._updateZIndex();
  8917. }
  8918. },
  8919. _updateOpacity: function () {
  8920. if (!this._map) { return; }
  8921. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8922. if (ielt9) { return; }
  8923. setOpacity(this._container, this.options.opacity);
  8924. var now = +new Date(),
  8925. nextFrame = false,
  8926. willPrune = false;
  8927. for (var key in this._tiles) {
  8928. var tile = this._tiles[key];
  8929. if (!tile.current || !tile.loaded) { continue; }
  8930. var fade = Math.min(1, (now - tile.loaded) / 200);
  8931. setOpacity(tile.el, fade);
  8932. if (fade < 1) {
  8933. nextFrame = true;
  8934. } else {
  8935. if (tile.active) {
  8936. willPrune = true;
  8937. } else {
  8938. this._onOpaqueTile(tile);
  8939. }
  8940. tile.active = true;
  8941. }
  8942. }
  8943. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  8944. if (nextFrame) {
  8945. cancelAnimFrame(this._fadeFrame);
  8946. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8947. }
  8948. },
  8949. _onOpaqueTile: falseFn,
  8950. _initContainer: function () {
  8951. if (this._container) { return; }
  8952. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  8953. this._updateZIndex();
  8954. if (this.options.opacity < 1) {
  8955. this._updateOpacity();
  8956. }
  8957. this.getPane().appendChild(this._container);
  8958. },
  8959. _updateLevels: function () {
  8960. var zoom = this._tileZoom,
  8961. maxZoom = this.options.maxZoom;
  8962. if (zoom === undefined) { return undefined; }
  8963. for (var z in this._levels) {
  8964. if (this._levels[z].el.children.length || z === zoom) {
  8965. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  8966. this._onUpdateLevel(z);
  8967. } else {
  8968. remove(this._levels[z].el);
  8969. this._removeTilesAtZoom(z);
  8970. this._onRemoveLevel(z);
  8971. delete this._levels[z];
  8972. }
  8973. }
  8974. var level = this._levels[zoom],
  8975. map = this._map;
  8976. if (!level) {
  8977. level = this._levels[zoom] = {};
  8978. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  8979. level.el.style.zIndex = maxZoom;
  8980. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  8981. level.zoom = zoom;
  8982. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  8983. // force the browser to consider the newly added element for transition
  8984. falseFn(level.el.offsetWidth);
  8985. this._onCreateLevel(level);
  8986. }
  8987. this._level = level;
  8988. return level;
  8989. },
  8990. _onUpdateLevel: falseFn,
  8991. _onRemoveLevel: falseFn,
  8992. _onCreateLevel: falseFn,
  8993. _pruneTiles: function () {
  8994. if (!this._map) {
  8995. return;
  8996. }
  8997. var key, tile;
  8998. var zoom = this._map.getZoom();
  8999. if (zoom > this.options.maxZoom ||
  9000. zoom < this.options.minZoom) {
  9001. this._removeAllTiles();
  9002. return;
  9003. }
  9004. for (key in this._tiles) {
  9005. tile = this._tiles[key];
  9006. tile.retain = tile.current;
  9007. }
  9008. for (key in this._tiles) {
  9009. tile = this._tiles[key];
  9010. if (tile.current && !tile.active) {
  9011. var coords = tile.coords;
  9012. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9013. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9014. }
  9015. }
  9016. }
  9017. for (key in this._tiles) {
  9018. if (!this._tiles[key].retain) {
  9019. this._removeTile(key);
  9020. }
  9021. }
  9022. },
  9023. _removeTilesAtZoom: function (zoom) {
  9024. for (var key in this._tiles) {
  9025. if (this._tiles[key].coords.z !== zoom) {
  9026. continue;
  9027. }
  9028. this._removeTile(key);
  9029. }
  9030. },
  9031. _removeAllTiles: function () {
  9032. for (var key in this._tiles) {
  9033. this._removeTile(key);
  9034. }
  9035. },
  9036. _invalidateAll: function () {
  9037. for (var z in this._levels) {
  9038. remove(this._levels[z].el);
  9039. this._onRemoveLevel(z);
  9040. delete this._levels[z];
  9041. }
  9042. this._removeAllTiles();
  9043. this._tileZoom = undefined;
  9044. },
  9045. _retainParent: function (x, y, z, minZoom) {
  9046. var x2 = Math.floor(x / 2),
  9047. y2 = Math.floor(y / 2),
  9048. z2 = z - 1,
  9049. coords2 = new Point(+x2, +y2);
  9050. coords2.z = +z2;
  9051. var key = this._tileCoordsToKey(coords2),
  9052. tile = this._tiles[key];
  9053. if (tile && tile.active) {
  9054. tile.retain = true;
  9055. return true;
  9056. } else if (tile && tile.loaded) {
  9057. tile.retain = true;
  9058. }
  9059. if (z2 > minZoom) {
  9060. return this._retainParent(x2, y2, z2, minZoom);
  9061. }
  9062. return false;
  9063. },
  9064. _retainChildren: function (x, y, z, maxZoom) {
  9065. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9066. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9067. var coords = new Point(i, j);
  9068. coords.z = z + 1;
  9069. var key = this._tileCoordsToKey(coords),
  9070. tile = this._tiles[key];
  9071. if (tile && tile.active) {
  9072. tile.retain = true;
  9073. continue;
  9074. } else if (tile && tile.loaded) {
  9075. tile.retain = true;
  9076. }
  9077. if (z + 1 < maxZoom) {
  9078. this._retainChildren(i, j, z + 1, maxZoom);
  9079. }
  9080. }
  9081. }
  9082. },
  9083. _resetView: function (e) {
  9084. var animating = e && (e.pinch || e.flyTo);
  9085. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9086. },
  9087. _animateZoom: function (e) {
  9088. this._setView(e.center, e.zoom, true, e.noUpdate);
  9089. },
  9090. _clampZoom: function (zoom) {
  9091. var options = this.options;
  9092. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9093. return options.minNativeZoom;
  9094. }
  9095. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9096. return options.maxNativeZoom;
  9097. }
  9098. return zoom;
  9099. },
  9100. _setView: function (center, zoom, noPrune, noUpdate) {
  9101. var tileZoom = this._clampZoom(Math.round(zoom));
  9102. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9103. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9104. tileZoom = undefined;
  9105. }
  9106. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9107. if (!noUpdate || tileZoomChanged) {
  9108. this._tileZoom = tileZoom;
  9109. if (this._abortLoading) {
  9110. this._abortLoading();
  9111. }
  9112. this._updateLevels();
  9113. this._resetGrid();
  9114. if (tileZoom !== undefined) {
  9115. this._update(center);
  9116. }
  9117. if (!noPrune) {
  9118. this._pruneTiles();
  9119. }
  9120. // Flag to prevent _updateOpacity from pruning tiles during
  9121. // a zoom anim or a pinch gesture
  9122. this._noPrune = !!noPrune;
  9123. }
  9124. this._setZoomTransforms(center, zoom);
  9125. },
  9126. _setZoomTransforms: function (center, zoom) {
  9127. for (var i in this._levels) {
  9128. this._setZoomTransform(this._levels[i], center, zoom);
  9129. }
  9130. },
  9131. _setZoomTransform: function (level, center, zoom) {
  9132. var scale = this._map.getZoomScale(zoom, level.zoom),
  9133. translate = level.origin.multiplyBy(scale)
  9134. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9135. if (any3d) {
  9136. setTransform(level.el, translate, scale);
  9137. } else {
  9138. setPosition(level.el, translate);
  9139. }
  9140. },
  9141. _resetGrid: function () {
  9142. var map = this._map,
  9143. crs = map.options.crs,
  9144. tileSize = this._tileSize = this.getTileSize(),
  9145. tileZoom = this._tileZoom;
  9146. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9147. if (bounds) {
  9148. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9149. }
  9150. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9151. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9152. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9153. ];
  9154. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9155. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9156. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9157. ];
  9158. },
  9159. _onMoveEnd: function () {
  9160. if (!this._map || this._map._animatingZoom) { return; }
  9161. this._update();
  9162. },
  9163. _getTiledPixelBounds: function (center) {
  9164. var map = this._map,
  9165. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9166. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9167. pixelCenter = map.project(center, this._tileZoom).floor(),
  9168. halfSize = map.getSize().divideBy(scale * 2);
  9169. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9170. },
  9171. // Private method to load tiles in the grid's active zoom level according to map bounds
  9172. _update: function (center) {
  9173. var map = this._map;
  9174. if (!map) { return; }
  9175. var zoom = this._clampZoom(map.getZoom());
  9176. if (center === undefined) { center = map.getCenter(); }
  9177. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9178. var pixelBounds = this._getTiledPixelBounds(center),
  9179. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9180. tileCenter = tileRange.getCenter(),
  9181. queue = [],
  9182. margin = this.options.keepBuffer,
  9183. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9184. tileRange.getTopRight().add([margin, -margin]));
  9185. // Sanity check: panic if the tile range contains Infinity somewhere.
  9186. if (!(isFinite(tileRange.min.x) &&
  9187. isFinite(tileRange.min.y) &&
  9188. isFinite(tileRange.max.x) &&
  9189. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9190. for (var key in this._tiles) {
  9191. var c = this._tiles[key].coords;
  9192. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9193. this._tiles[key].current = false;
  9194. }
  9195. }
  9196. // _update just loads more tiles. If the tile zoom level differs too much
  9197. // from the map's, let _setView reset levels and prune old tiles.
  9198. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9199. // create a queue of coordinates to load tiles from
  9200. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9201. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9202. var coords = new Point(i, j);
  9203. coords.z = this._tileZoom;
  9204. if (!this._isValidTile(coords)) { continue; }
  9205. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9206. if (tile) {
  9207. tile.current = true;
  9208. } else {
  9209. queue.push(coords);
  9210. }
  9211. }
  9212. }
  9213. // sort tile queue to load tiles in order of their distance to center
  9214. queue.sort(function (a, b) {
  9215. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9216. });
  9217. if (queue.length !== 0) {
  9218. // if it's the first batch of tiles to load
  9219. if (!this._loading) {
  9220. this._loading = true;
  9221. // @event loading: Event
  9222. // Fired when the grid layer starts loading tiles.
  9223. this.fire('loading');
  9224. }
  9225. // create DOM fragment to append tiles in one batch
  9226. var fragment = document.createDocumentFragment();
  9227. for (i = 0; i < queue.length; i++) {
  9228. this._addTile(queue[i], fragment);
  9229. }
  9230. this._level.el.appendChild(fragment);
  9231. }
  9232. },
  9233. _isValidTile: function (coords) {
  9234. var crs = this._map.options.crs;
  9235. if (!crs.infinite) {
  9236. // don't load tile if it's out of bounds and not wrapped
  9237. var bounds = this._globalTileRange;
  9238. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9239. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9240. }
  9241. if (!this.options.bounds) { return true; }
  9242. // don't load tile if it doesn't intersect the bounds in options
  9243. var tileBounds = this._tileCoordsToBounds(coords);
  9244. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9245. },
  9246. _keyToBounds: function (key) {
  9247. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9248. },
  9249. _tileCoordsToNwSe: function (coords) {
  9250. var map = this._map,
  9251. tileSize = this.getTileSize(),
  9252. nwPoint = coords.scaleBy(tileSize),
  9253. sePoint = nwPoint.add(tileSize),
  9254. nw = map.unproject(nwPoint, coords.z),
  9255. se = map.unproject(sePoint, coords.z);
  9256. return [nw, se];
  9257. },
  9258. // converts tile coordinates to its geographical bounds
  9259. _tileCoordsToBounds: function (coords) {
  9260. var bp = this._tileCoordsToNwSe(coords),
  9261. bounds = new LatLngBounds(bp[0], bp[1]);
  9262. if (!this.options.noWrap) {
  9263. bounds = this._map.wrapLatLngBounds(bounds);
  9264. }
  9265. return bounds;
  9266. },
  9267. // converts tile coordinates to key for the tile cache
  9268. _tileCoordsToKey: function (coords) {
  9269. return coords.x + ':' + coords.y + ':' + coords.z;
  9270. },
  9271. // converts tile cache key to coordinates
  9272. _keyToTileCoords: function (key) {
  9273. var k = key.split(':'),
  9274. coords = new Point(+k[0], +k[1]);
  9275. coords.z = +k[2];
  9276. return coords;
  9277. },
  9278. _removeTile: function (key) {
  9279. var tile = this._tiles[key];
  9280. if (!tile) { return; }
  9281. remove(tile.el);
  9282. delete this._tiles[key];
  9283. // @event tileunload: TileEvent
  9284. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9285. this.fire('tileunload', {
  9286. tile: tile.el,
  9287. coords: this._keyToTileCoords(key)
  9288. });
  9289. },
  9290. _initTile: function (tile) {
  9291. addClass(tile, 'leaflet-tile');
  9292. var tileSize = this.getTileSize();
  9293. tile.style.width = tileSize.x + 'px';
  9294. tile.style.height = tileSize.y + 'px';
  9295. tile.onselectstart = falseFn;
  9296. tile.onmousemove = falseFn;
  9297. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9298. if (ielt9 && this.options.opacity < 1) {
  9299. setOpacity(tile, this.options.opacity);
  9300. }
  9301. // without this hack, tiles disappear after zoom on Chrome for Android
  9302. // https://github.com/Leaflet/Leaflet/issues/2078
  9303. if (android && !android23) {
  9304. tile.style.WebkitBackfaceVisibility = 'hidden';
  9305. }
  9306. },
  9307. _addTile: function (coords, container) {
  9308. var tilePos = this._getTilePos(coords),
  9309. key = this._tileCoordsToKey(coords);
  9310. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9311. this._initTile(tile);
  9312. // if createTile is defined with a second argument ("done" callback),
  9313. // we know that tile is async and will be ready later; otherwise
  9314. if (this.createTile.length < 2) {
  9315. // mark tile as ready, but delay one frame for opacity animation to happen
  9316. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9317. }
  9318. setPosition(tile, tilePos);
  9319. // save tile in cache
  9320. this._tiles[key] = {
  9321. el: tile,
  9322. coords: coords,
  9323. current: true
  9324. };
  9325. container.appendChild(tile);
  9326. // @event tileloadstart: TileEvent
  9327. // Fired when a tile is requested and starts loading.
  9328. this.fire('tileloadstart', {
  9329. tile: tile,
  9330. coords: coords
  9331. });
  9332. },
  9333. _tileReady: function (coords, err, tile) {
  9334. if (err) {
  9335. // @event tileerror: TileErrorEvent
  9336. // Fired when there is an error loading a tile.
  9337. this.fire('tileerror', {
  9338. error: err,
  9339. tile: tile,
  9340. coords: coords
  9341. });
  9342. }
  9343. var key = this._tileCoordsToKey(coords);
  9344. tile = this._tiles[key];
  9345. if (!tile) { return; }
  9346. tile.loaded = +new Date();
  9347. if (this._map._fadeAnimated) {
  9348. setOpacity(tile.el, 0);
  9349. cancelAnimFrame(this._fadeFrame);
  9350. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9351. } else {
  9352. tile.active = true;
  9353. this._pruneTiles();
  9354. }
  9355. if (!err) {
  9356. addClass(tile.el, 'leaflet-tile-loaded');
  9357. // @event tileload: TileEvent
  9358. // Fired when a tile loads.
  9359. this.fire('tileload', {
  9360. tile: tile.el,
  9361. coords: coords
  9362. });
  9363. }
  9364. if (this._noTilesToLoad()) {
  9365. this._loading = false;
  9366. // @event load: Event
  9367. // Fired when the grid layer loaded all visible tiles.
  9368. this.fire('load');
  9369. if (ielt9 || !this._map._fadeAnimated) {
  9370. requestAnimFrame(this._pruneTiles, this);
  9371. } else {
  9372. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9373. // to trigger a pruning.
  9374. setTimeout(bind(this._pruneTiles, this), 250);
  9375. }
  9376. }
  9377. },
  9378. _getTilePos: function (coords) {
  9379. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9380. },
  9381. _wrapCoords: function (coords) {
  9382. var newCoords = new Point(
  9383. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9384. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9385. newCoords.z = coords.z;
  9386. return newCoords;
  9387. },
  9388. _pxBoundsToTileRange: function (bounds) {
  9389. var tileSize = this.getTileSize();
  9390. return new Bounds(
  9391. bounds.min.unscaleBy(tileSize).floor(),
  9392. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9393. },
  9394. _noTilesToLoad: function () {
  9395. for (var key in this._tiles) {
  9396. if (!this._tiles[key].loaded) { return false; }
  9397. }
  9398. return true;
  9399. }
  9400. });
  9401. // @factory L.gridLayer(options?: GridLayer options)
  9402. // Creates a new instance of GridLayer with the supplied options.
  9403. function gridLayer(options) {
  9404. return new GridLayer(options);
  9405. }
  9406. /*
  9407. * @class TileLayer
  9408. * @inherits GridLayer
  9409. * @aka L.TileLayer
  9410. * Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`.
  9411. *
  9412. * @example
  9413. *
  9414. * ```js
  9415. * L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'}).addTo(map);
  9416. * ```
  9417. *
  9418. * @section URL template
  9419. * @example
  9420. *
  9421. * A string of the following form:
  9422. *
  9423. * ```
  9424. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9425. * ```
  9426. *
  9427. * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add "&commat;2x" to the URL to load retina tiles.
  9428. *
  9429. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9430. *
  9431. * ```
  9432. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9433. * ```
  9434. */
  9435. var TileLayer = GridLayer.extend({
  9436. // @section
  9437. // @aka TileLayer options
  9438. options: {
  9439. // @option minZoom: Number = 0
  9440. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9441. minZoom: 0,
  9442. // @option maxZoom: Number = 18
  9443. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9444. maxZoom: 18,
  9445. // @option subdomains: String|String[] = 'abc'
  9446. // Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.
  9447. subdomains: 'abc',
  9448. // @option errorTileUrl: String = ''
  9449. // URL to the tile image to show in place of the tile that failed to load.
  9450. errorTileUrl: '',
  9451. // @option zoomOffset: Number = 0
  9452. // The zoom number used in tile URLs will be offset with this value.
  9453. zoomOffset: 0,
  9454. // @option tms: Boolean = false
  9455. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9456. tms: false,
  9457. // @option zoomReverse: Boolean = false
  9458. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9459. zoomReverse: false,
  9460. // @option detectRetina: Boolean = false
  9461. // If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.
  9462. detectRetina: false,
  9463. // @option crossOrigin: Boolean|String = false
  9464. // Whether the crossOrigin attribute will be added to the tiles.
  9465. // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
  9466. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9467. crossOrigin: false
  9468. },
  9469. initialize: function (url, options) {
  9470. this._url = url;
  9471. options = setOptions(this, options);
  9472. // detecting retina displays, adjusting tileSize and zoom levels
  9473. if (options.detectRetina && retina && options.maxZoom > 0) {
  9474. options.tileSize = Math.floor(options.tileSize / 2);
  9475. if (!options.zoomReverse) {
  9476. options.zoomOffset++;
  9477. options.maxZoom--;
  9478. } else {
  9479. options.zoomOffset--;
  9480. options.minZoom++;
  9481. }
  9482. options.minZoom = Math.max(0, options.minZoom);
  9483. }
  9484. if (typeof options.subdomains === 'string') {
  9485. options.subdomains = options.subdomains.split('');
  9486. }
  9487. // for https://github.com/Leaflet/Leaflet/issues/137
  9488. if (!android) {
  9489. this.on('tileunload', this._onTileRemove);
  9490. }
  9491. },
  9492. // @method setUrl(url: String, noRedraw?: Boolean): this
  9493. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9494. // If the URL does not change, the layer will not be redrawn unless
  9495. // the noRedraw parameter is set to false.
  9496. setUrl: function (url, noRedraw) {
  9497. if (this._url === url && noRedraw === undefined) {
  9498. noRedraw = true;
  9499. }
  9500. this._url = url;
  9501. if (!noRedraw) {
  9502. this.redraw();
  9503. }
  9504. return this;
  9505. },
  9506. // @method createTile(coords: Object, done?: Function): HTMLElement
  9507. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9508. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9509. // callback is called when the tile has been loaded.
  9510. createTile: function (coords, done) {
  9511. var tile = document.createElement('img');
  9512. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9513. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9514. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  9515. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  9516. }
  9517. /*
  9518. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9519. http://www.w3.org/TR/WCAG20-TECHS/H67
  9520. */
  9521. tile.alt = '';
  9522. /*
  9523. Set role="presentation" to force screen readers to ignore this
  9524. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9525. */
  9526. tile.setAttribute('role', 'presentation');
  9527. tile.src = this.getTileUrl(coords);
  9528. return tile;
  9529. },
  9530. // @section Extension methods
  9531. // @uninheritable
  9532. // Layers extending `TileLayer` might reimplement the following method.
  9533. // @method getTileUrl(coords: Object): String
  9534. // Called only internally, returns the URL for a tile given its coordinates.
  9535. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9536. getTileUrl: function (coords) {
  9537. var data = {
  9538. r: retina ? '@2x' : '',
  9539. s: this._getSubdomain(coords),
  9540. x: coords.x,
  9541. y: coords.y,
  9542. z: this._getZoomForUrl()
  9543. };
  9544. if (this._map && !this._map.options.crs.infinite) {
  9545. var invertedY = this._globalTileRange.max.y - coords.y;
  9546. if (this.options.tms) {
  9547. data['y'] = invertedY;
  9548. }
  9549. data['-y'] = invertedY;
  9550. }
  9551. return template(this._url, extend(data, this.options));
  9552. },
  9553. _tileOnLoad: function (done, tile) {
  9554. // For https://github.com/Leaflet/Leaflet/issues/3332
  9555. if (ielt9) {
  9556. setTimeout(bind(done, this, null, tile), 0);
  9557. } else {
  9558. done(null, tile);
  9559. }
  9560. },
  9561. _tileOnError: function (done, tile, e) {
  9562. var errorUrl = this.options.errorTileUrl;
  9563. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9564. tile.src = errorUrl;
  9565. }
  9566. done(e, tile);
  9567. },
  9568. _onTileRemove: function (e) {
  9569. e.tile.onload = null;
  9570. },
  9571. _getZoomForUrl: function () {
  9572. var zoom = this._tileZoom,
  9573. maxZoom = this.options.maxZoom,
  9574. zoomReverse = this.options.zoomReverse,
  9575. zoomOffset = this.options.zoomOffset;
  9576. if (zoomReverse) {
  9577. zoom = maxZoom - zoom;
  9578. }
  9579. return zoom + zoomOffset;
  9580. },
  9581. _getSubdomain: function (tilePoint) {
  9582. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9583. return this.options.subdomains[index];
  9584. },
  9585. // stops loading all tiles in the background layer
  9586. _abortLoading: function () {
  9587. var i, tile;
  9588. for (i in this._tiles) {
  9589. if (this._tiles[i].coords.z !== this._tileZoom) {
  9590. tile = this._tiles[i].el;
  9591. tile.onload = falseFn;
  9592. tile.onerror = falseFn;
  9593. if (!tile.complete) {
  9594. tile.src = emptyImageUrl;
  9595. remove(tile);
  9596. delete this._tiles[i];
  9597. }
  9598. }
  9599. }
  9600. },
  9601. _removeTile: function (key) {
  9602. var tile = this._tiles[key];
  9603. if (!tile) { return; }
  9604. // Cancels any pending http requests associated with the tile
  9605. // unless we're on Android's stock browser,
  9606. // see https://github.com/Leaflet/Leaflet/issues/137
  9607. if (!androidStock) {
  9608. tile.el.setAttribute('src', emptyImageUrl);
  9609. }
  9610. return GridLayer.prototype._removeTile.call(this, key);
  9611. },
  9612. _tileReady: function (coords, err, tile) {
  9613. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  9614. return;
  9615. }
  9616. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  9617. }
  9618. });
  9619. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9620. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9621. function tileLayer(url, options) {
  9622. return new TileLayer(url, options);
  9623. }
  9624. /*
  9625. * @class TileLayer.WMS
  9626. * @inherits TileLayer
  9627. * @aka L.TileLayer.WMS
  9628. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9629. *
  9630. * @example
  9631. *
  9632. * ```js
  9633. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9634. * layers: 'nexrad-n0r-900913',
  9635. * format: 'image/png',
  9636. * transparent: true,
  9637. * attribution: "Weather data © 2012 IEM Nexrad"
  9638. * });
  9639. * ```
  9640. */
  9641. var TileLayerWMS = TileLayer.extend({
  9642. // @section
  9643. // @aka TileLayer.WMS options
  9644. // If any custom options not documented here are used, they will be sent to the
  9645. // WMS server as extra parameters in each request URL. This can be useful for
  9646. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9647. defaultWmsParams: {
  9648. service: 'WMS',
  9649. request: 'GetMap',
  9650. // @option layers: String = ''
  9651. // **(required)** Comma-separated list of WMS layers to show.
  9652. layers: '',
  9653. // @option styles: String = ''
  9654. // Comma-separated list of WMS styles.
  9655. styles: '',
  9656. // @option format: String = 'image/jpeg'
  9657. // WMS image format (use `'image/png'` for layers with transparency).
  9658. format: 'image/jpeg',
  9659. // @option transparent: Boolean = false
  9660. // If `true`, the WMS service will return images with transparency.
  9661. transparent: false,
  9662. // @option version: String = '1.1.1'
  9663. // Version of the WMS service to use
  9664. version: '1.1.1'
  9665. },
  9666. options: {
  9667. // @option crs: CRS = null
  9668. // Coordinate Reference System to use for the WMS requests, defaults to
  9669. // map CRS. Don't change this if you're not sure what it means.
  9670. crs: null,
  9671. // @option uppercase: Boolean = false
  9672. // If `true`, WMS request parameter keys will be uppercase.
  9673. uppercase: false
  9674. },
  9675. initialize: function (url, options) {
  9676. this._url = url;
  9677. var wmsParams = extend({}, this.defaultWmsParams);
  9678. // all keys that are not TileLayer options go to WMS params
  9679. for (var i in options) {
  9680. if (!(i in this.options)) {
  9681. wmsParams[i] = options[i];
  9682. }
  9683. }
  9684. options = setOptions(this, options);
  9685. var realRetina = options.detectRetina && retina ? 2 : 1;
  9686. var tileSize = this.getTileSize();
  9687. wmsParams.width = tileSize.x * realRetina;
  9688. wmsParams.height = tileSize.y * realRetina;
  9689. this.wmsParams = wmsParams;
  9690. },
  9691. onAdd: function (map) {
  9692. this._crs = this.options.crs || map.options.crs;
  9693. this._wmsVersion = parseFloat(this.wmsParams.version);
  9694. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9695. this.wmsParams[projectionKey] = this._crs.code;
  9696. TileLayer.prototype.onAdd.call(this, map);
  9697. },
  9698. getTileUrl: function (coords) {
  9699. var tileBounds = this._tileCoordsToNwSe(coords),
  9700. crs = this._crs,
  9701. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  9702. min = bounds.min,
  9703. max = bounds.max,
  9704. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9705. [min.y, min.x, max.y, max.x] :
  9706. [min.x, min.y, max.x, max.y]).join(','),
  9707. url = TileLayer.prototype.getTileUrl.call(this, coords);
  9708. return url +
  9709. getParamString(this.wmsParams, url, this.options.uppercase) +
  9710. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9711. },
  9712. // @method setParams(params: Object, noRedraw?: Boolean): this
  9713. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9714. setParams: function (params, noRedraw) {
  9715. extend(this.wmsParams, params);
  9716. if (!noRedraw) {
  9717. this.redraw();
  9718. }
  9719. return this;
  9720. }
  9721. });
  9722. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9723. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9724. function tileLayerWMS(url, options) {
  9725. return new TileLayerWMS(url, options);
  9726. }
  9727. TileLayer.WMS = TileLayerWMS;
  9728. tileLayer.wms = tileLayerWMS;
  9729. /*
  9730. * @class Renderer
  9731. * @inherits Layer
  9732. * @aka L.Renderer
  9733. *
  9734. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9735. * DOM container of the renderer, its bounds, and its zoom animation.
  9736. *
  9737. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9738. * itself can be added or removed to the map. All paths use a renderer, which can
  9739. * be implicit (the map will decide the type of renderer and use it automatically)
  9740. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9741. *
  9742. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9743. *
  9744. * @event update: Event
  9745. * Fired when the renderer updates its bounds, center and zoom, for example when
  9746. * its map has moved
  9747. */
  9748. var Renderer = Layer.extend({
  9749. // @section
  9750. // @aka Renderer options
  9751. options: {
  9752. // @option padding: Number = 0.1
  9753. // How much to extend the clip area around the map view (relative to its size)
  9754. // e.g. 0.1 would be 10% of map view in each direction
  9755. padding: 0.1,
  9756. // @option tolerance: Number = 0
  9757. // How much to extend click tolerance round a path/object on the map
  9758. tolerance : 0
  9759. },
  9760. initialize: function (options) {
  9761. setOptions(this, options);
  9762. stamp(this);
  9763. this._layers = this._layers || {};
  9764. },
  9765. onAdd: function () {
  9766. if (!this._container) {
  9767. this._initContainer(); // defined by renderer implementations
  9768. if (this._zoomAnimated) {
  9769. addClass(this._container, 'leaflet-zoom-animated');
  9770. }
  9771. }
  9772. this.getPane().appendChild(this._container);
  9773. this._update();
  9774. this.on('update', this._updatePaths, this);
  9775. },
  9776. onRemove: function () {
  9777. this.off('update', this._updatePaths, this);
  9778. this._destroyContainer();
  9779. },
  9780. getEvents: function () {
  9781. var events = {
  9782. viewreset: this._reset,
  9783. zoom: this._onZoom,
  9784. moveend: this._update,
  9785. zoomend: this._onZoomEnd
  9786. };
  9787. if (this._zoomAnimated) {
  9788. events.zoomanim = this._onAnimZoom;
  9789. }
  9790. return events;
  9791. },
  9792. _onAnimZoom: function (ev) {
  9793. this._updateTransform(ev.center, ev.zoom);
  9794. },
  9795. _onZoom: function () {
  9796. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9797. },
  9798. _updateTransform: function (center, zoom) {
  9799. var scale = this._map.getZoomScale(zoom, this._zoom),
  9800. position = getPosition(this._container),
  9801. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9802. currentCenterPoint = this._map.project(this._center, zoom),
  9803. destCenterPoint = this._map.project(center, zoom),
  9804. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9805. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9806. if (any3d) {
  9807. setTransform(this._container, topLeftOffset, scale);
  9808. } else {
  9809. setPosition(this._container, topLeftOffset);
  9810. }
  9811. },
  9812. _reset: function () {
  9813. this._update();
  9814. this._updateTransform(this._center, this._zoom);
  9815. for (var id in this._layers) {
  9816. this._layers[id]._reset();
  9817. }
  9818. },
  9819. _onZoomEnd: function () {
  9820. for (var id in this._layers) {
  9821. this._layers[id]._project();
  9822. }
  9823. },
  9824. _updatePaths: function () {
  9825. for (var id in this._layers) {
  9826. this._layers[id]._update();
  9827. }
  9828. },
  9829. _update: function () {
  9830. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9831. // Subclasses are responsible of firing the 'update' event.
  9832. var p = this.options.padding,
  9833. size = this._map.getSize(),
  9834. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9835. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9836. this._center = this._map.getCenter();
  9837. this._zoom = this._map.getZoom();
  9838. }
  9839. });
  9840. /*
  9841. * @class Canvas
  9842. * @inherits Renderer
  9843. * @aka L.Canvas
  9844. *
  9845. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9846. * Inherits `Renderer`.
  9847. *
  9848. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9849. * available in all web browsers, notably IE8, and overlapping geometries might
  9850. * not display properly in some edge cases.
  9851. *
  9852. * @example
  9853. *
  9854. * Use Canvas by default for all paths in the map:
  9855. *
  9856. * ```js
  9857. * var map = L.map('map', {
  9858. * renderer: L.canvas()
  9859. * });
  9860. * ```
  9861. *
  9862. * Use a Canvas renderer with extra padding for specific vector geometries:
  9863. *
  9864. * ```js
  9865. * var map = L.map('map');
  9866. * var myRenderer = L.canvas({ padding: 0.5 });
  9867. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9868. * var circle = L.circle( center, { renderer: myRenderer } );
  9869. * ```
  9870. */
  9871. var Canvas = Renderer.extend({
  9872. getEvents: function () {
  9873. var events = Renderer.prototype.getEvents.call(this);
  9874. events.viewprereset = this._onViewPreReset;
  9875. return events;
  9876. },
  9877. _onViewPreReset: function () {
  9878. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9879. this._postponeUpdatePaths = true;
  9880. },
  9881. onAdd: function () {
  9882. Renderer.prototype.onAdd.call(this);
  9883. // Redraw vectors since canvas is cleared upon removal,
  9884. // in case of removing the renderer itself from the map.
  9885. this._draw();
  9886. },
  9887. _initContainer: function () {
  9888. var container = this._container = document.createElement('canvas');
  9889. on(container, 'mousemove', throttle(this._onMouseMove, 32, this), this);
  9890. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9891. on(container, 'mouseout', this._handleMouseOut, this);
  9892. this._ctx = container.getContext('2d');
  9893. },
  9894. _destroyContainer: function () {
  9895. cancelAnimFrame(this._redrawRequest);
  9896. delete this._ctx;
  9897. remove(this._container);
  9898. off(this._container);
  9899. delete this._container;
  9900. },
  9901. _updatePaths: function () {
  9902. if (this._postponeUpdatePaths) { return; }
  9903. var layer;
  9904. this._redrawBounds = null;
  9905. for (var id in this._layers) {
  9906. layer = this._layers[id];
  9907. layer._update();
  9908. }
  9909. this._redraw();
  9910. },
  9911. _update: function () {
  9912. if (this._map._animatingZoom && this._bounds) { return; }
  9913. Renderer.prototype._update.call(this);
  9914. var b = this._bounds,
  9915. container = this._container,
  9916. size = b.getSize(),
  9917. m = retina ? 2 : 1;
  9918. setPosition(container, b.min);
  9919. // set canvas size (also clearing it); use double size on retina
  9920. container.width = m * size.x;
  9921. container.height = m * size.y;
  9922. container.style.width = size.x + 'px';
  9923. container.style.height = size.y + 'px';
  9924. if (retina) {
  9925. this._ctx.scale(2, 2);
  9926. }
  9927. // translate so we use the same path coordinates after canvas element moves
  9928. this._ctx.translate(-b.min.x, -b.min.y);
  9929. // Tell paths to redraw themselves
  9930. this.fire('update');
  9931. },
  9932. _reset: function () {
  9933. Renderer.prototype._reset.call(this);
  9934. if (this._postponeUpdatePaths) {
  9935. this._postponeUpdatePaths = false;
  9936. this._updatePaths();
  9937. }
  9938. },
  9939. _initPath: function (layer) {
  9940. this._updateDashArray(layer);
  9941. this._layers[stamp(layer)] = layer;
  9942. var order = layer._order = {
  9943. layer: layer,
  9944. prev: this._drawLast,
  9945. next: null
  9946. };
  9947. if (this._drawLast) { this._drawLast.next = order; }
  9948. this._drawLast = order;
  9949. this._drawFirst = this._drawFirst || this._drawLast;
  9950. },
  9951. _addPath: function (layer) {
  9952. this._requestRedraw(layer);
  9953. },
  9954. _removePath: function (layer) {
  9955. var order = layer._order;
  9956. var next = order.next;
  9957. var prev = order.prev;
  9958. if (next) {
  9959. next.prev = prev;
  9960. } else {
  9961. this._drawLast = prev;
  9962. }
  9963. if (prev) {
  9964. prev.next = next;
  9965. } else {
  9966. this._drawFirst = next;
  9967. }
  9968. delete layer._order;
  9969. delete this._layers[stamp(layer)];
  9970. this._requestRedraw(layer);
  9971. },
  9972. _updatePath: function (layer) {
  9973. // Redraw the union of the layer's old pixel
  9974. // bounds and the new pixel bounds.
  9975. this._extendRedrawBounds(layer);
  9976. layer._project();
  9977. layer._update();
  9978. // The redraw will extend the redraw bounds
  9979. // with the new pixel bounds.
  9980. this._requestRedraw(layer);
  9981. },
  9982. _updateStyle: function (layer) {
  9983. this._updateDashArray(layer);
  9984. this._requestRedraw(layer);
  9985. },
  9986. _updateDashArray: function (layer) {
  9987. if (typeof layer.options.dashArray === 'string') {
  9988. var parts = layer.options.dashArray.split(/[, ]+/),
  9989. dashArray = [],
  9990. dashValue,
  9991. i;
  9992. for (i = 0; i < parts.length; i++) {
  9993. dashValue = Number(parts[i]);
  9994. // Ignore dash array containing invalid lengths
  9995. if (isNaN(dashValue)) { return; }
  9996. dashArray.push(dashValue);
  9997. }
  9998. layer.options._dashArray = dashArray;
  9999. } else {
  10000. layer.options._dashArray = layer.options.dashArray;
  10001. }
  10002. },
  10003. _requestRedraw: function (layer) {
  10004. if (!this._map) { return; }
  10005. this._extendRedrawBounds(layer);
  10006. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10007. },
  10008. _extendRedrawBounds: function (layer) {
  10009. if (layer._pxBounds) {
  10010. var padding = (layer.options.weight || 0) + 1;
  10011. this._redrawBounds = this._redrawBounds || new Bounds();
  10012. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10013. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10014. }
  10015. },
  10016. _redraw: function () {
  10017. this._redrawRequest = null;
  10018. if (this._redrawBounds) {
  10019. this._redrawBounds.min._floor();
  10020. this._redrawBounds.max._ceil();
  10021. }
  10022. this._clear(); // clear layers in redraw bounds
  10023. this._draw(); // draw layers
  10024. this._redrawBounds = null;
  10025. },
  10026. _clear: function () {
  10027. var bounds = this._redrawBounds;
  10028. if (bounds) {
  10029. var size = bounds.getSize();
  10030. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10031. } else {
  10032. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10033. }
  10034. },
  10035. _draw: function () {
  10036. var layer, bounds = this._redrawBounds;
  10037. this._ctx.save();
  10038. if (bounds) {
  10039. var size = bounds.getSize();
  10040. this._ctx.beginPath();
  10041. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10042. this._ctx.clip();
  10043. }
  10044. this._drawing = true;
  10045. for (var order = this._drawFirst; order; order = order.next) {
  10046. layer = order.layer;
  10047. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10048. layer._updatePath();
  10049. }
  10050. }
  10051. this._drawing = false;
  10052. this._ctx.restore(); // Restore state before clipping.
  10053. },
  10054. _updatePoly: function (layer, closed) {
  10055. if (!this._drawing) { return; }
  10056. var i, j, len2, p,
  10057. parts = layer._parts,
  10058. len = parts.length,
  10059. ctx = this._ctx;
  10060. if (!len) { return; }
  10061. ctx.beginPath();
  10062. for (i = 0; i < len; i++) {
  10063. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10064. p = parts[i][j];
  10065. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10066. }
  10067. if (closed) {
  10068. ctx.closePath();
  10069. }
  10070. }
  10071. this._fillStroke(ctx, layer);
  10072. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10073. },
  10074. _updateCircle: function (layer) {
  10075. if (!this._drawing || layer._empty()) { return; }
  10076. var p = layer._point,
  10077. ctx = this._ctx,
  10078. r = Math.max(Math.round(layer._radius), 1),
  10079. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10080. if (s !== 1) {
  10081. ctx.save();
  10082. ctx.scale(1, s);
  10083. }
  10084. ctx.beginPath();
  10085. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10086. if (s !== 1) {
  10087. ctx.restore();
  10088. }
  10089. this._fillStroke(ctx, layer);
  10090. },
  10091. _fillStroke: function (ctx, layer) {
  10092. var options = layer.options;
  10093. if (options.fill) {
  10094. ctx.globalAlpha = options.fillOpacity;
  10095. ctx.fillStyle = options.fillColor || options.color;
  10096. ctx.fill(options.fillRule || 'evenodd');
  10097. }
  10098. if (options.stroke && options.weight !== 0) {
  10099. if (ctx.setLineDash) {
  10100. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10101. }
  10102. ctx.globalAlpha = options.opacity;
  10103. ctx.lineWidth = options.weight;
  10104. ctx.strokeStyle = options.color;
  10105. ctx.lineCap = options.lineCap;
  10106. ctx.lineJoin = options.lineJoin;
  10107. ctx.stroke();
  10108. }
  10109. },
  10110. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10111. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10112. _onClick: function (e) {
  10113. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10114. for (var order = this._drawFirst; order; order = order.next) {
  10115. layer = order.layer;
  10116. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  10117. clickedLayer = layer;
  10118. }
  10119. }
  10120. if (clickedLayer) {
  10121. fakeStop(e);
  10122. this._fireEvent([clickedLayer], e);
  10123. }
  10124. },
  10125. _onMouseMove: function (e) {
  10126. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10127. var point = this._map.mouseEventToLayerPoint(e);
  10128. this._handleMouseHover(e, point);
  10129. },
  10130. _handleMouseOut: function (e) {
  10131. var layer = this._hoveredLayer;
  10132. if (layer) {
  10133. // if we're leaving the layer, fire mouseout
  10134. removeClass(this._container, 'leaflet-interactive');
  10135. this._fireEvent([layer], e, 'mouseout');
  10136. this._hoveredLayer = null;
  10137. }
  10138. },
  10139. _handleMouseHover: function (e, point) {
  10140. var layer, candidateHoveredLayer;
  10141. for (var order = this._drawFirst; order; order = order.next) {
  10142. layer = order.layer;
  10143. if (layer.options.interactive && layer._containsPoint(point)) {
  10144. candidateHoveredLayer = layer;
  10145. }
  10146. }
  10147. if (candidateHoveredLayer !== this._hoveredLayer) {
  10148. this._handleMouseOut(e);
  10149. if (candidateHoveredLayer) {
  10150. addClass(this._container, 'leaflet-interactive'); // change cursor
  10151. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10152. this._hoveredLayer = candidateHoveredLayer;
  10153. }
  10154. }
  10155. if (this._hoveredLayer) {
  10156. this._fireEvent([this._hoveredLayer], e);
  10157. }
  10158. },
  10159. _fireEvent: function (layers, e, type) {
  10160. this._map._fireDOMEvent(e, type || e.type, layers);
  10161. },
  10162. _bringToFront: function (layer) {
  10163. var order = layer._order;
  10164. if (!order) { return; }
  10165. var next = order.next;
  10166. var prev = order.prev;
  10167. if (next) {
  10168. next.prev = prev;
  10169. } else {
  10170. // Already last
  10171. return;
  10172. }
  10173. if (prev) {
  10174. prev.next = next;
  10175. } else if (next) {
  10176. // Update first entry unless this is the
  10177. // single entry
  10178. this._drawFirst = next;
  10179. }
  10180. order.prev = this._drawLast;
  10181. this._drawLast.next = order;
  10182. order.next = null;
  10183. this._drawLast = order;
  10184. this._requestRedraw(layer);
  10185. },
  10186. _bringToBack: function (layer) {
  10187. var order = layer._order;
  10188. if (!order) { return; }
  10189. var next = order.next;
  10190. var prev = order.prev;
  10191. if (prev) {
  10192. prev.next = next;
  10193. } else {
  10194. // Already first
  10195. return;
  10196. }
  10197. if (next) {
  10198. next.prev = prev;
  10199. } else if (prev) {
  10200. // Update last entry unless this is the
  10201. // single entry
  10202. this._drawLast = prev;
  10203. }
  10204. order.prev = null;
  10205. order.next = this._drawFirst;
  10206. this._drawFirst.prev = order;
  10207. this._drawFirst = order;
  10208. this._requestRedraw(layer);
  10209. }
  10210. });
  10211. // @factory L.canvas(options?: Renderer options)
  10212. // Creates a Canvas renderer with the given options.
  10213. function canvas$1(options) {
  10214. return canvas ? new Canvas(options) : null;
  10215. }
  10216. /*
  10217. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10218. */
  10219. var vmlCreate = (function () {
  10220. try {
  10221. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10222. return function (name) {
  10223. return document.createElement('<lvml:' + name + ' class="lvml">');
  10224. };
  10225. } catch (e) {
  10226. return function (name) {
  10227. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10228. };
  10229. }
  10230. })();
  10231. /*
  10232. * @class SVG
  10233. *
  10234. *
  10235. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10236. * with old versions of Internet Explorer.
  10237. */
  10238. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10239. var vmlMixin = {
  10240. _initContainer: function () {
  10241. this._container = create$1('div', 'leaflet-vml-container');
  10242. },
  10243. _update: function () {
  10244. if (this._map._animatingZoom) { return; }
  10245. Renderer.prototype._update.call(this);
  10246. this.fire('update');
  10247. },
  10248. _initPath: function (layer) {
  10249. var container = layer._container = vmlCreate('shape');
  10250. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10251. container.coordsize = '1 1';
  10252. layer._path = vmlCreate('path');
  10253. container.appendChild(layer._path);
  10254. this._updateStyle(layer);
  10255. this._layers[stamp(layer)] = layer;
  10256. },
  10257. _addPath: function (layer) {
  10258. var container = layer._container;
  10259. this._container.appendChild(container);
  10260. if (layer.options.interactive) {
  10261. layer.addInteractiveTarget(container);
  10262. }
  10263. },
  10264. _removePath: function (layer) {
  10265. var container = layer._container;
  10266. remove(container);
  10267. layer.removeInteractiveTarget(container);
  10268. delete this._layers[stamp(layer)];
  10269. },
  10270. _updateStyle: function (layer) {
  10271. var stroke = layer._stroke,
  10272. fill = layer._fill,
  10273. options = layer.options,
  10274. container = layer._container;
  10275. container.stroked = !!options.stroke;
  10276. container.filled = !!options.fill;
  10277. if (options.stroke) {
  10278. if (!stroke) {
  10279. stroke = layer._stroke = vmlCreate('stroke');
  10280. }
  10281. container.appendChild(stroke);
  10282. stroke.weight = options.weight + 'px';
  10283. stroke.color = options.color;
  10284. stroke.opacity = options.opacity;
  10285. if (options.dashArray) {
  10286. stroke.dashStyle = isArray(options.dashArray) ?
  10287. options.dashArray.join(' ') :
  10288. options.dashArray.replace(/( *, *)/g, ' ');
  10289. } else {
  10290. stroke.dashStyle = '';
  10291. }
  10292. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10293. stroke.joinstyle = options.lineJoin;
  10294. } else if (stroke) {
  10295. container.removeChild(stroke);
  10296. layer._stroke = null;
  10297. }
  10298. if (options.fill) {
  10299. if (!fill) {
  10300. fill = layer._fill = vmlCreate('fill');
  10301. }
  10302. container.appendChild(fill);
  10303. fill.color = options.fillColor || options.color;
  10304. fill.opacity = options.fillOpacity;
  10305. } else if (fill) {
  10306. container.removeChild(fill);
  10307. layer._fill = null;
  10308. }
  10309. },
  10310. _updateCircle: function (layer) {
  10311. var p = layer._point.round(),
  10312. r = Math.round(layer._radius),
  10313. r2 = Math.round(layer._radiusY || r);
  10314. this._setPath(layer, layer._empty() ? 'M0 0' :
  10315. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10316. },
  10317. _setPath: function (layer, path) {
  10318. layer._path.v = path;
  10319. },
  10320. _bringToFront: function (layer) {
  10321. toFront(layer._container);
  10322. },
  10323. _bringToBack: function (layer) {
  10324. toBack(layer._container);
  10325. }
  10326. };
  10327. var create$2 = vml ? vmlCreate : svgCreate;
  10328. /*
  10329. * @class SVG
  10330. * @inherits Renderer
  10331. * @aka L.SVG
  10332. *
  10333. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10334. * Inherits `Renderer`.
  10335. *
  10336. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  10337. * available in all web browsers, notably Android 2.x and 3.x.
  10338. *
  10339. * Although SVG is not available on IE7 and IE8, these browsers support
  10340. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10341. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10342. * this case.
  10343. *
  10344. * @example
  10345. *
  10346. * Use SVG by default for all paths in the map:
  10347. *
  10348. * ```js
  10349. * var map = L.map('map', {
  10350. * renderer: L.svg()
  10351. * });
  10352. * ```
  10353. *
  10354. * Use a SVG renderer with extra padding for specific vector geometries:
  10355. *
  10356. * ```js
  10357. * var map = L.map('map');
  10358. * var myRenderer = L.svg({ padding: 0.5 });
  10359. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10360. * var circle = L.circle( center, { renderer: myRenderer } );
  10361. * ```
  10362. */
  10363. var SVG = Renderer.extend({
  10364. getEvents: function () {
  10365. var events = Renderer.prototype.getEvents.call(this);
  10366. events.zoomstart = this._onZoomStart;
  10367. return events;
  10368. },
  10369. _initContainer: function () {
  10370. this._container = create$2('svg');
  10371. // makes it possible to click through svg root; we'll reset it back in individual paths
  10372. this._container.setAttribute('pointer-events', 'none');
  10373. this._rootGroup = create$2('g');
  10374. this._container.appendChild(this._rootGroup);
  10375. },
  10376. _destroyContainer: function () {
  10377. remove(this._container);
  10378. off(this._container);
  10379. delete this._container;
  10380. delete this._rootGroup;
  10381. delete this._svgSize;
  10382. },
  10383. _onZoomStart: function () {
  10384. // Drag-then-pinch interactions might mess up the center and zoom.
  10385. // In this case, the easiest way to prevent this is re-do the renderer
  10386. // bounds and padding when the zooming starts.
  10387. this._update();
  10388. },
  10389. _update: function () {
  10390. if (this._map._animatingZoom && this._bounds) { return; }
  10391. Renderer.prototype._update.call(this);
  10392. var b = this._bounds,
  10393. size = b.getSize(),
  10394. container = this._container;
  10395. // set size of svg-container if changed
  10396. if (!this._svgSize || !this._svgSize.equals(size)) {
  10397. this._svgSize = size;
  10398. container.setAttribute('width', size.x);
  10399. container.setAttribute('height', size.y);
  10400. }
  10401. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10402. setPosition(container, b.min);
  10403. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10404. this.fire('update');
  10405. },
  10406. // methods below are called by vector layers implementations
  10407. _initPath: function (layer) {
  10408. var path = layer._path = create$2('path');
  10409. // @namespace Path
  10410. // @option className: String = null
  10411. // Custom class name set on an element. Only for SVG renderer.
  10412. if (layer.options.className) {
  10413. addClass(path, layer.options.className);
  10414. }
  10415. if (layer.options.interactive) {
  10416. addClass(path, 'leaflet-interactive');
  10417. }
  10418. this._updateStyle(layer);
  10419. this._layers[stamp(layer)] = layer;
  10420. },
  10421. _addPath: function (layer) {
  10422. if (!this._rootGroup) { this._initContainer(); }
  10423. this._rootGroup.appendChild(layer._path);
  10424. layer.addInteractiveTarget(layer._path);
  10425. },
  10426. _removePath: function (layer) {
  10427. remove(layer._path);
  10428. layer.removeInteractiveTarget(layer._path);
  10429. delete this._layers[stamp(layer)];
  10430. },
  10431. _updatePath: function (layer) {
  10432. layer._project();
  10433. layer._update();
  10434. },
  10435. _updateStyle: function (layer) {
  10436. var path = layer._path,
  10437. options = layer.options;
  10438. if (!path) { return; }
  10439. if (options.stroke) {
  10440. path.setAttribute('stroke', options.color);
  10441. path.setAttribute('stroke-opacity', options.opacity);
  10442. path.setAttribute('stroke-width', options.weight);
  10443. path.setAttribute('stroke-linecap', options.lineCap);
  10444. path.setAttribute('stroke-linejoin', options.lineJoin);
  10445. if (options.dashArray) {
  10446. path.setAttribute('stroke-dasharray', options.dashArray);
  10447. } else {
  10448. path.removeAttribute('stroke-dasharray');
  10449. }
  10450. if (options.dashOffset) {
  10451. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10452. } else {
  10453. path.removeAttribute('stroke-dashoffset');
  10454. }
  10455. } else {
  10456. path.setAttribute('stroke', 'none');
  10457. }
  10458. if (options.fill) {
  10459. path.setAttribute('fill', options.fillColor || options.color);
  10460. path.setAttribute('fill-opacity', options.fillOpacity);
  10461. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10462. } else {
  10463. path.setAttribute('fill', 'none');
  10464. }
  10465. },
  10466. _updatePoly: function (layer, closed) {
  10467. this._setPath(layer, pointsToPath(layer._parts, closed));
  10468. },
  10469. _updateCircle: function (layer) {
  10470. var p = layer._point,
  10471. r = Math.max(Math.round(layer._radius), 1),
  10472. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10473. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10474. // drawing a circle with two half-arcs
  10475. var d = layer._empty() ? 'M0 0' :
  10476. 'M' + (p.x - r) + ',' + p.y +
  10477. arc + (r * 2) + ',0 ' +
  10478. arc + (-r * 2) + ',0 ';
  10479. this._setPath(layer, d);
  10480. },
  10481. _setPath: function (layer, path) {
  10482. layer._path.setAttribute('d', path);
  10483. },
  10484. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10485. _bringToFront: function (layer) {
  10486. toFront(layer._path);
  10487. },
  10488. _bringToBack: function (layer) {
  10489. toBack(layer._path);
  10490. }
  10491. });
  10492. if (vml) {
  10493. SVG.include(vmlMixin);
  10494. }
  10495. // @namespace SVG
  10496. // @factory L.svg(options?: Renderer options)
  10497. // Creates a SVG renderer with the given options.
  10498. function svg$1(options) {
  10499. return svg || vml ? new SVG(options) : null;
  10500. }
  10501. Map.include({
  10502. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10503. // Returns the instance of `Renderer` that should be used to render the given
  10504. // `Path`. It will ensure that the `renderer` options of the map and paths
  10505. // are respected, and that the renderers do exist on the map.
  10506. getRenderer: function (layer) {
  10507. // @namespace Path; @option renderer: Renderer
  10508. // Use this specific instance of `Renderer` for this path. Takes
  10509. // precedence over the map's [default renderer](#map-renderer).
  10510. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10511. if (!renderer) {
  10512. renderer = this._renderer = this._createRenderer();
  10513. }
  10514. if (!this.hasLayer(renderer)) {
  10515. this.addLayer(renderer);
  10516. }
  10517. return renderer;
  10518. },
  10519. _getPaneRenderer: function (name) {
  10520. if (name === 'overlayPane' || name === undefined) {
  10521. return false;
  10522. }
  10523. var renderer = this._paneRenderers[name];
  10524. if (renderer === undefined) {
  10525. renderer = this._createRenderer({pane: name});
  10526. this._paneRenderers[name] = renderer;
  10527. }
  10528. return renderer;
  10529. },
  10530. _createRenderer: function (options) {
  10531. // @namespace Map; @option preferCanvas: Boolean = false
  10532. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10533. // By default, all `Path`s are rendered in a `SVG` renderer.
  10534. return (this.options.preferCanvas && canvas$1(options)) || svg$1(options);
  10535. }
  10536. });
  10537. /*
  10538. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10539. */
  10540. /*
  10541. * @class Rectangle
  10542. * @aka L.Rectangle
  10543. * @inherits Polygon
  10544. *
  10545. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10546. *
  10547. * @example
  10548. *
  10549. * ```js
  10550. * // define rectangle geographical bounds
  10551. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10552. *
  10553. * // create an orange rectangle
  10554. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10555. *
  10556. * // zoom the map to the rectangle bounds
  10557. * map.fitBounds(bounds);
  10558. * ```
  10559. *
  10560. */
  10561. var Rectangle = Polygon.extend({
  10562. initialize: function (latLngBounds, options) {
  10563. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10564. },
  10565. // @method setBounds(latLngBounds: LatLngBounds): this
  10566. // Redraws the rectangle with the passed bounds.
  10567. setBounds: function (latLngBounds) {
  10568. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10569. },
  10570. _boundsToLatLngs: function (latLngBounds) {
  10571. latLngBounds = toLatLngBounds(latLngBounds);
  10572. return [
  10573. latLngBounds.getSouthWest(),
  10574. latLngBounds.getNorthWest(),
  10575. latLngBounds.getNorthEast(),
  10576. latLngBounds.getSouthEast()
  10577. ];
  10578. }
  10579. });
  10580. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10581. function rectangle(latLngBounds, options) {
  10582. return new Rectangle(latLngBounds, options);
  10583. }
  10584. SVG.create = create$2;
  10585. SVG.pointsToPath = pointsToPath;
  10586. GeoJSON.geometryToLayer = geometryToLayer;
  10587. GeoJSON.coordsToLatLng = coordsToLatLng;
  10588. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10589. GeoJSON.latLngToCoords = latLngToCoords;
  10590. GeoJSON.latLngsToCoords = latLngsToCoords;
  10591. GeoJSON.getFeature = getFeature;
  10592. GeoJSON.asFeature = asFeature;
  10593. /*
  10594. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10595. * (zoom to a selected bounding box), enabled by default.
  10596. */
  10597. // @namespace Map
  10598. // @section Interaction Options
  10599. Map.mergeOptions({
  10600. // @option boxZoom: Boolean = true
  10601. // Whether the map can be zoomed to a rectangular area specified by
  10602. // dragging the mouse while pressing the shift key.
  10603. boxZoom: true
  10604. });
  10605. var BoxZoom = Handler.extend({
  10606. initialize: function (map) {
  10607. this._map = map;
  10608. this._container = map._container;
  10609. this._pane = map._panes.overlayPane;
  10610. this._resetStateTimeout = 0;
  10611. map.on('unload', this._destroy, this);
  10612. },
  10613. addHooks: function () {
  10614. on(this._container, 'mousedown', this._onMouseDown, this);
  10615. },
  10616. removeHooks: function () {
  10617. off(this._container, 'mousedown', this._onMouseDown, this);
  10618. },
  10619. moved: function () {
  10620. return this._moved;
  10621. },
  10622. _destroy: function () {
  10623. remove(this._pane);
  10624. delete this._pane;
  10625. },
  10626. _resetState: function () {
  10627. this._resetStateTimeout = 0;
  10628. this._moved = false;
  10629. },
  10630. _clearDeferredResetState: function () {
  10631. if (this._resetStateTimeout !== 0) {
  10632. clearTimeout(this._resetStateTimeout);
  10633. this._resetStateTimeout = 0;
  10634. }
  10635. },
  10636. _onMouseDown: function (e) {
  10637. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  10638. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10639. // will interrupt the interaction and orphan a box element in the container.
  10640. this._clearDeferredResetState();
  10641. this._resetState();
  10642. disableTextSelection();
  10643. disableImageDrag();
  10644. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10645. on(document, {
  10646. contextmenu: stop,
  10647. mousemove: this._onMouseMove,
  10648. mouseup: this._onMouseUp,
  10649. keydown: this._onKeyDown
  10650. }, this);
  10651. },
  10652. _onMouseMove: function (e) {
  10653. if (!this._moved) {
  10654. this._moved = true;
  10655. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10656. addClass(this._container, 'leaflet-crosshair');
  10657. this._map.fire('boxzoomstart');
  10658. }
  10659. this._point = this._map.mouseEventToContainerPoint(e);
  10660. var bounds = new Bounds(this._point, this._startPoint),
  10661. size = bounds.getSize();
  10662. setPosition(this._box, bounds.min);
  10663. this._box.style.width = size.x + 'px';
  10664. this._box.style.height = size.y + 'px';
  10665. },
  10666. _finish: function () {
  10667. if (this._moved) {
  10668. remove(this._box);
  10669. removeClass(this._container, 'leaflet-crosshair');
  10670. }
  10671. enableTextSelection();
  10672. enableImageDrag();
  10673. off(document, {
  10674. contextmenu: stop,
  10675. mousemove: this._onMouseMove,
  10676. mouseup: this._onMouseUp,
  10677. keydown: this._onKeyDown
  10678. }, this);
  10679. },
  10680. _onMouseUp: function (e) {
  10681. if ((e.which !== 1) && (e.button !== 1)) { return; }
  10682. this._finish();
  10683. if (!this._moved) { return; }
  10684. // Postpone to next JS tick so internal click event handling
  10685. // still see it as "moved".
  10686. this._clearDeferredResetState();
  10687. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10688. var bounds = new LatLngBounds(
  10689. this._map.containerPointToLatLng(this._startPoint),
  10690. this._map.containerPointToLatLng(this._point));
  10691. this._map
  10692. .fitBounds(bounds)
  10693. .fire('boxzoomend', {boxZoomBounds: bounds});
  10694. },
  10695. _onKeyDown: function (e) {
  10696. if (e.keyCode === 27) {
  10697. this._finish();
  10698. }
  10699. }
  10700. });
  10701. // @section Handlers
  10702. // @property boxZoom: Handler
  10703. // Box (shift-drag with mouse) zoom handler.
  10704. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10705. /*
  10706. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10707. */
  10708. // @namespace Map
  10709. // @section Interaction Options
  10710. Map.mergeOptions({
  10711. // @option doubleClickZoom: Boolean|String = true
  10712. // Whether the map can be zoomed in by double clicking on it and
  10713. // zoomed out by double clicking while holding shift. If passed
  10714. // `'center'`, double-click zoom will zoom to the center of the
  10715. // view regardless of where the mouse was.
  10716. doubleClickZoom: true
  10717. });
  10718. var DoubleClickZoom = Handler.extend({
  10719. addHooks: function () {
  10720. this._map.on('dblclick', this._onDoubleClick, this);
  10721. },
  10722. removeHooks: function () {
  10723. this._map.off('dblclick', this._onDoubleClick, this);
  10724. },
  10725. _onDoubleClick: function (e) {
  10726. var map = this._map,
  10727. oldZoom = map.getZoom(),
  10728. delta = map.options.zoomDelta,
  10729. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10730. if (map.options.doubleClickZoom === 'center') {
  10731. map.setZoom(zoom);
  10732. } else {
  10733. map.setZoomAround(e.containerPoint, zoom);
  10734. }
  10735. }
  10736. });
  10737. // @section Handlers
  10738. //
  10739. // Map properties include interaction handlers that allow you to control
  10740. // interaction behavior in runtime, enabling or disabling certain features such
  10741. // as dragging or touch zoom (see `Handler` methods). For example:
  10742. //
  10743. // ```js
  10744. // map.doubleClickZoom.disable();
  10745. // ```
  10746. //
  10747. // @property doubleClickZoom: Handler
  10748. // Double click zoom handler.
  10749. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10750. /*
  10751. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10752. */
  10753. // @namespace Map
  10754. // @section Interaction Options
  10755. Map.mergeOptions({
  10756. // @option dragging: Boolean = true
  10757. // Whether the map be draggable with mouse/touch or not.
  10758. dragging: true,
  10759. // @section Panning Inertia Options
  10760. // @option inertia: Boolean = *
  10761. // If enabled, panning of the map will have an inertia effect where
  10762. // the map builds momentum while dragging and continues moving in
  10763. // the same direction for some time. Feels especially nice on touch
  10764. // devices. Enabled by default unless running on old Android devices.
  10765. inertia: !android23,
  10766. // @option inertiaDeceleration: Number = 3000
  10767. // The rate with which the inertial movement slows down, in pixels/second².
  10768. inertiaDeceleration: 3400, // px/s^2
  10769. // @option inertiaMaxSpeed: Number = Infinity
  10770. // Max speed of the inertial movement, in pixels/second.
  10771. inertiaMaxSpeed: Infinity, // px/s
  10772. // @option easeLinearity: Number = 0.2
  10773. easeLinearity: 0.2,
  10774. // TODO refactor, move to CRS
  10775. // @option worldCopyJump: Boolean = false
  10776. // With this option enabled, the map tracks when you pan to another "copy"
  10777. // of the world and seamlessly jumps to the original one so that all overlays
  10778. // like markers and vector layers are still visible.
  10779. worldCopyJump: false,
  10780. // @option maxBoundsViscosity: Number = 0.0
  10781. // If `maxBounds` is set, this option will control how solid the bounds
  10782. // are when dragging the map around. The default value of `0.0` allows the
  10783. // user to drag outside the bounds at normal speed, higher values will
  10784. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10785. // solid, preventing the user from dragging outside the bounds.
  10786. maxBoundsViscosity: 0.0
  10787. });
  10788. var Drag = Handler.extend({
  10789. addHooks: function () {
  10790. if (!this._draggable) {
  10791. var map = this._map;
  10792. this._draggable = new Draggable(map._mapPane, map._container);
  10793. this._draggable.on({
  10794. dragstart: this._onDragStart,
  10795. drag: this._onDrag,
  10796. dragend: this._onDragEnd
  10797. }, this);
  10798. this._draggable.on('predrag', this._onPreDragLimit, this);
  10799. if (map.options.worldCopyJump) {
  10800. this._draggable.on('predrag', this._onPreDragWrap, this);
  10801. map.on('zoomend', this._onZoomEnd, this);
  10802. map.whenReady(this._onZoomEnd, this);
  10803. }
  10804. }
  10805. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10806. this._draggable.enable();
  10807. this._positions = [];
  10808. this._times = [];
  10809. },
  10810. removeHooks: function () {
  10811. removeClass(this._map._container, 'leaflet-grab');
  10812. removeClass(this._map._container, 'leaflet-touch-drag');
  10813. this._draggable.disable();
  10814. },
  10815. moved: function () {
  10816. return this._draggable && this._draggable._moved;
  10817. },
  10818. moving: function () {
  10819. return this._draggable && this._draggable._moving;
  10820. },
  10821. _onDragStart: function () {
  10822. var map = this._map;
  10823. map._stop();
  10824. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10825. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10826. this._offsetLimit = toBounds(
  10827. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10828. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10829. .add(this._map.getSize()));
  10830. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10831. } else {
  10832. this._offsetLimit = null;
  10833. }
  10834. map
  10835. .fire('movestart')
  10836. .fire('dragstart');
  10837. if (map.options.inertia) {
  10838. this._positions = [];
  10839. this._times = [];
  10840. }
  10841. },
  10842. _onDrag: function (e) {
  10843. if (this._map.options.inertia) {
  10844. var time = this._lastTime = +new Date(),
  10845. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10846. this._positions.push(pos);
  10847. this._times.push(time);
  10848. this._prunePositions(time);
  10849. }
  10850. this._map
  10851. .fire('move', e)
  10852. .fire('drag', e);
  10853. },
  10854. _prunePositions: function (time) {
  10855. while (this._positions.length > 1 && time - this._times[0] > 50) {
  10856. this._positions.shift();
  10857. this._times.shift();
  10858. }
  10859. },
  10860. _onZoomEnd: function () {
  10861. var pxCenter = this._map.getSize().divideBy(2),
  10862. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10863. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10864. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10865. },
  10866. _viscousLimit: function (value, threshold) {
  10867. return value - (value - threshold) * this._viscosity;
  10868. },
  10869. _onPreDragLimit: function () {
  10870. if (!this._viscosity || !this._offsetLimit) { return; }
  10871. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10872. var limit = this._offsetLimit;
  10873. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  10874. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  10875. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  10876. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  10877. this._draggable._newPos = this._draggable._startPos.add(offset);
  10878. },
  10879. _onPreDragWrap: function () {
  10880. // TODO refactor to be able to adjust map pane position after zoom
  10881. var worldWidth = this._worldWidth,
  10882. halfWidth = Math.round(worldWidth / 2),
  10883. dx = this._initialWorldOffset,
  10884. x = this._draggable._newPos.x,
  10885. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10886. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10887. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10888. this._draggable._absPos = this._draggable._newPos.clone();
  10889. this._draggable._newPos.x = newX;
  10890. },
  10891. _onDragEnd: function (e) {
  10892. var map = this._map,
  10893. options = map.options,
  10894. noInertia = !options.inertia || this._times.length < 2;
  10895. map.fire('dragend', e);
  10896. if (noInertia) {
  10897. map.fire('moveend');
  10898. } else {
  10899. this._prunePositions(+new Date());
  10900. var direction = this._lastPos.subtract(this._positions[0]),
  10901. duration = (this._lastTime - this._times[0]) / 1000,
  10902. ease = options.easeLinearity,
  10903. speedVector = direction.multiplyBy(ease / duration),
  10904. speed = speedVector.distanceTo([0, 0]),
  10905. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10906. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10907. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10908. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10909. if (!offset.x && !offset.y) {
  10910. map.fire('moveend');
  10911. } else {
  10912. offset = map._limitOffset(offset, map.options.maxBounds);
  10913. requestAnimFrame(function () {
  10914. map.panBy(offset, {
  10915. duration: decelerationDuration,
  10916. easeLinearity: ease,
  10917. noMoveStart: true,
  10918. animate: true
  10919. });
  10920. });
  10921. }
  10922. }
  10923. }
  10924. });
  10925. // @section Handlers
  10926. // @property dragging: Handler
  10927. // Map dragging handler (by both mouse and touch).
  10928. Map.addInitHook('addHandler', 'dragging', Drag);
  10929. /*
  10930. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10931. */
  10932. // @namespace Map
  10933. // @section Keyboard Navigation Options
  10934. Map.mergeOptions({
  10935. // @option keyboard: Boolean = true
  10936. // Makes the map focusable and allows users to navigate the map with keyboard
  10937. // arrows and `+`/`-` keys.
  10938. keyboard: true,
  10939. // @option keyboardPanDelta: Number = 80
  10940. // Amount of pixels to pan when pressing an arrow key.
  10941. keyboardPanDelta: 80
  10942. });
  10943. var Keyboard = Handler.extend({
  10944. keyCodes: {
  10945. left: [37],
  10946. right: [39],
  10947. down: [40],
  10948. up: [38],
  10949. zoomIn: [187, 107, 61, 171],
  10950. zoomOut: [189, 109, 54, 173]
  10951. },
  10952. initialize: function (map) {
  10953. this._map = map;
  10954. this._setPanDelta(map.options.keyboardPanDelta);
  10955. this._setZoomDelta(map.options.zoomDelta);
  10956. },
  10957. addHooks: function () {
  10958. var container = this._map._container;
  10959. // make the container focusable by tabbing
  10960. if (container.tabIndex <= 0) {
  10961. container.tabIndex = '0';
  10962. }
  10963. on(container, {
  10964. focus: this._onFocus,
  10965. blur: this._onBlur,
  10966. mousedown: this._onMouseDown
  10967. }, this);
  10968. this._map.on({
  10969. focus: this._addHooks,
  10970. blur: this._removeHooks
  10971. }, this);
  10972. },
  10973. removeHooks: function () {
  10974. this._removeHooks();
  10975. off(this._map._container, {
  10976. focus: this._onFocus,
  10977. blur: this._onBlur,
  10978. mousedown: this._onMouseDown
  10979. }, this);
  10980. this._map.off({
  10981. focus: this._addHooks,
  10982. blur: this._removeHooks
  10983. }, this);
  10984. },
  10985. _onMouseDown: function () {
  10986. if (this._focused) { return; }
  10987. var body = document.body,
  10988. docEl = document.documentElement,
  10989. top = body.scrollTop || docEl.scrollTop,
  10990. left = body.scrollLeft || docEl.scrollLeft;
  10991. this._map._container.focus();
  10992. window.scrollTo(left, top);
  10993. },
  10994. _onFocus: function () {
  10995. this._focused = true;
  10996. this._map.fire('focus');
  10997. },
  10998. _onBlur: function () {
  10999. this._focused = false;
  11000. this._map.fire('blur');
  11001. },
  11002. _setPanDelta: function (panDelta) {
  11003. var keys = this._panKeys = {},
  11004. codes = this.keyCodes,
  11005. i, len;
  11006. for (i = 0, len = codes.left.length; i < len; i++) {
  11007. keys[codes.left[i]] = [-1 * panDelta, 0];
  11008. }
  11009. for (i = 0, len = codes.right.length; i < len; i++) {
  11010. keys[codes.right[i]] = [panDelta, 0];
  11011. }
  11012. for (i = 0, len = codes.down.length; i < len; i++) {
  11013. keys[codes.down[i]] = [0, panDelta];
  11014. }
  11015. for (i = 0, len = codes.up.length; i < len; i++) {
  11016. keys[codes.up[i]] = [0, -1 * panDelta];
  11017. }
  11018. },
  11019. _setZoomDelta: function (zoomDelta) {
  11020. var keys = this._zoomKeys = {},
  11021. codes = this.keyCodes,
  11022. i, len;
  11023. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11024. keys[codes.zoomIn[i]] = zoomDelta;
  11025. }
  11026. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11027. keys[codes.zoomOut[i]] = -zoomDelta;
  11028. }
  11029. },
  11030. _addHooks: function () {
  11031. on(document, 'keydown', this._onKeyDown, this);
  11032. },
  11033. _removeHooks: function () {
  11034. off(document, 'keydown', this._onKeyDown, this);
  11035. },
  11036. _onKeyDown: function (e) {
  11037. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11038. var key = e.keyCode,
  11039. map = this._map,
  11040. offset;
  11041. if (key in this._panKeys) {
  11042. if (!map._panAnim || !map._panAnim._inProgress) {
  11043. offset = this._panKeys[key];
  11044. if (e.shiftKey) {
  11045. offset = toPoint(offset).multiplyBy(3);
  11046. }
  11047. map.panBy(offset);
  11048. if (map.options.maxBounds) {
  11049. map.panInsideBounds(map.options.maxBounds);
  11050. }
  11051. }
  11052. } else if (key in this._zoomKeys) {
  11053. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11054. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11055. map.closePopup();
  11056. } else {
  11057. return;
  11058. }
  11059. stop(e);
  11060. }
  11061. });
  11062. // @section Handlers
  11063. // @section Handlers
  11064. // @property keyboard: Handler
  11065. // Keyboard navigation handler.
  11066. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11067. /*
  11068. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11069. */
  11070. // @namespace Map
  11071. // @section Interaction Options
  11072. Map.mergeOptions({
  11073. // @section Mousewheel options
  11074. // @option scrollWheelZoom: Boolean|String = true
  11075. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11076. // it will zoom to the center of the view regardless of where the mouse was.
  11077. scrollWheelZoom: true,
  11078. // @option wheelDebounceTime: Number = 40
  11079. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11080. // user can't zoom via wheel more often than once per 40 ms.
  11081. wheelDebounceTime: 40,
  11082. // @option wheelPxPerZoomLevel: Number = 60
  11083. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11084. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11085. // faster (and vice versa).
  11086. wheelPxPerZoomLevel: 60
  11087. });
  11088. var ScrollWheelZoom = Handler.extend({
  11089. addHooks: function () {
  11090. on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  11091. this._delta = 0;
  11092. },
  11093. removeHooks: function () {
  11094. off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  11095. },
  11096. _onWheelScroll: function (e) {
  11097. var delta = getWheelDelta(e);
  11098. var debounce = this._map.options.wheelDebounceTime;
  11099. this._delta += delta;
  11100. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11101. if (!this._startTime) {
  11102. this._startTime = +new Date();
  11103. }
  11104. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11105. clearTimeout(this._timer);
  11106. this._timer = setTimeout(bind(this._performZoom, this), left);
  11107. stop(e);
  11108. },
  11109. _performZoom: function () {
  11110. var map = this._map,
  11111. zoom = map.getZoom(),
  11112. snap = this._map.options.zoomSnap || 0;
  11113. map._stop(); // stop panning and fly animations if any
  11114. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11115. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11116. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11117. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11118. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11119. this._delta = 0;
  11120. this._startTime = null;
  11121. if (!delta) { return; }
  11122. if (map.options.scrollWheelZoom === 'center') {
  11123. map.setZoom(zoom + delta);
  11124. } else {
  11125. map.setZoomAround(this._lastMousePos, zoom + delta);
  11126. }
  11127. }
  11128. });
  11129. // @section Handlers
  11130. // @property scrollWheelZoom: Handler
  11131. // Scroll wheel zoom handler.
  11132. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11133. /*
  11134. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  11135. */
  11136. // @namespace Map
  11137. // @section Interaction Options
  11138. Map.mergeOptions({
  11139. // @section Touch interaction options
  11140. // @option tap: Boolean = true
  11141. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  11142. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  11143. tap: true,
  11144. // @option tapTolerance: Number = 15
  11145. // The max number of pixels a user can shift his finger during touch
  11146. // for it to be considered a valid tap.
  11147. tapTolerance: 15
  11148. });
  11149. var Tap = Handler.extend({
  11150. addHooks: function () {
  11151. on(this._map._container, 'touchstart', this._onDown, this);
  11152. },
  11153. removeHooks: function () {
  11154. off(this._map._container, 'touchstart', this._onDown, this);
  11155. },
  11156. _onDown: function (e) {
  11157. if (!e.touches) { return; }
  11158. preventDefault(e);
  11159. this._fireClick = true;
  11160. // don't simulate click or track longpress if more than 1 touch
  11161. if (e.touches.length > 1) {
  11162. this._fireClick = false;
  11163. clearTimeout(this._holdTimeout);
  11164. return;
  11165. }
  11166. var first = e.touches[0],
  11167. el = first.target;
  11168. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11169. // if touching a link, highlight it
  11170. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  11171. addClass(el, 'leaflet-active');
  11172. }
  11173. // simulate long hold but setting a timeout
  11174. this._holdTimeout = setTimeout(bind(function () {
  11175. if (this._isTapValid()) {
  11176. this._fireClick = false;
  11177. this._onUp();
  11178. this._simulateEvent('contextmenu', first);
  11179. }
  11180. }, this), 1000);
  11181. this._simulateEvent('mousedown', first);
  11182. on(document, {
  11183. touchmove: this._onMove,
  11184. touchend: this._onUp
  11185. }, this);
  11186. },
  11187. _onUp: function (e) {
  11188. clearTimeout(this._holdTimeout);
  11189. off(document, {
  11190. touchmove: this._onMove,
  11191. touchend: this._onUp
  11192. }, this);
  11193. if (this._fireClick && e && e.changedTouches) {
  11194. var first = e.changedTouches[0],
  11195. el = first.target;
  11196. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  11197. removeClass(el, 'leaflet-active');
  11198. }
  11199. this._simulateEvent('mouseup', first);
  11200. // simulate click if the touch didn't move too much
  11201. if (this._isTapValid()) {
  11202. this._simulateEvent('click', first);
  11203. }
  11204. }
  11205. },
  11206. _isTapValid: function () {
  11207. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11208. },
  11209. _onMove: function (e) {
  11210. var first = e.touches[0];
  11211. this._newPos = new Point(first.clientX, first.clientY);
  11212. this._simulateEvent('mousemove', first);
  11213. },
  11214. _simulateEvent: function (type, e) {
  11215. var simulatedEvent = document.createEvent('MouseEvents');
  11216. simulatedEvent._simulated = true;
  11217. e.target._simulatedClick = true;
  11218. simulatedEvent.initMouseEvent(
  11219. type, true, true, window, 1,
  11220. e.screenX, e.screenY,
  11221. e.clientX, e.clientY,
  11222. false, false, false, false, 0, null);
  11223. e.target.dispatchEvent(simulatedEvent);
  11224. }
  11225. });
  11226. // @section Handlers
  11227. // @property tap: Handler
  11228. // Mobile touch hacks (quick tap and touch hold) handler.
  11229. if (touch && !pointer) {
  11230. Map.addInitHook('addHandler', 'tap', Tap);
  11231. }
  11232. /*
  11233. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11234. */
  11235. // @namespace Map
  11236. // @section Interaction Options
  11237. Map.mergeOptions({
  11238. // @section Touch interaction options
  11239. // @option touchZoom: Boolean|String = *
  11240. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11241. // passed `'center'`, it will zoom to the center of the view regardless of
  11242. // where the touch events (fingers) were. Enabled for touch-capable web
  11243. // browsers except for old Androids.
  11244. touchZoom: touch && !android23,
  11245. // @option bounceAtZoomLimits: Boolean = true
  11246. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11247. // and then bounce back when pinch-zooming.
  11248. bounceAtZoomLimits: true
  11249. });
  11250. var TouchZoom = Handler.extend({
  11251. addHooks: function () {
  11252. addClass(this._map._container, 'leaflet-touch-zoom');
  11253. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11254. },
  11255. removeHooks: function () {
  11256. removeClass(this._map._container, 'leaflet-touch-zoom');
  11257. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11258. },
  11259. _onTouchStart: function (e) {
  11260. var map = this._map;
  11261. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11262. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11263. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11264. this._centerPoint = map.getSize()._divideBy(2);
  11265. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11266. if (map.options.touchZoom !== 'center') {
  11267. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11268. }
  11269. this._startDist = p1.distanceTo(p2);
  11270. this._startZoom = map.getZoom();
  11271. this._moved = false;
  11272. this._zooming = true;
  11273. map._stop();
  11274. on(document, 'touchmove', this._onTouchMove, this);
  11275. on(document, 'touchend', this._onTouchEnd, this);
  11276. preventDefault(e);
  11277. },
  11278. _onTouchMove: function (e) {
  11279. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11280. var map = this._map,
  11281. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11282. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11283. scale = p1.distanceTo(p2) / this._startDist;
  11284. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11285. if (!map.options.bounceAtZoomLimits && (
  11286. (this._zoom < map.getMinZoom() && scale < 1) ||
  11287. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11288. this._zoom = map._limitZoom(this._zoom);
  11289. }
  11290. if (map.options.touchZoom === 'center') {
  11291. this._center = this._startLatLng;
  11292. if (scale === 1) { return; }
  11293. } else {
  11294. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11295. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11296. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11297. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11298. }
  11299. if (!this._moved) {
  11300. map._moveStart(true, false);
  11301. this._moved = true;
  11302. }
  11303. cancelAnimFrame(this._animRequest);
  11304. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  11305. this._animRequest = requestAnimFrame(moveFn, this, true);
  11306. preventDefault(e);
  11307. },
  11308. _onTouchEnd: function () {
  11309. if (!this._moved || !this._zooming) {
  11310. this._zooming = false;
  11311. return;
  11312. }
  11313. this._zooming = false;
  11314. cancelAnimFrame(this._animRequest);
  11315. off(document, 'touchmove', this._onTouchMove);
  11316. off(document, 'touchend', this._onTouchEnd);
  11317. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11318. if (this._map.options.zoomAnimation) {
  11319. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11320. } else {
  11321. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11322. }
  11323. }
  11324. });
  11325. // @section Handlers
  11326. // @property touchZoom: Handler
  11327. // Touch zoom handler.
  11328. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11329. Map.BoxZoom = BoxZoom;
  11330. Map.DoubleClickZoom = DoubleClickZoom;
  11331. Map.Drag = Drag;
  11332. Map.Keyboard = Keyboard;
  11333. Map.ScrollWheelZoom = ScrollWheelZoom;
  11334. Map.Tap = Tap;
  11335. Map.TouchZoom = TouchZoom;
  11336. Object.freeze = freeze;
  11337. export { version, Control, control, Browser, Evented, Mixin, Util, Class, Handler, extend, bind, stamp, setOptions, DomEvent, DomUtil, PosAnimation, Draggable, LineUtil, PolyUtil, Point, toPoint as point, Bounds, toBounds as bounds, Transformation, toTransformation as transformation, index as Projection, LatLng, toLatLng as latLng, LatLngBounds, toLatLngBounds as latLngBounds, CRS, GeoJSON, geoJSON, geoJson, Layer, LayerGroup, layerGroup, FeatureGroup, featureGroup, ImageOverlay, imageOverlay, VideoOverlay, videoOverlay, SVGOverlay, svgOverlay, DivOverlay, Popup, popup, Tooltip, tooltip, Icon, icon, DivIcon, divIcon, Marker, marker, TileLayer, tileLayer, GridLayer, gridLayer, SVG, svg$1 as svg, Renderer, Canvas, canvas$1 as canvas, Path, CircleMarker, circleMarker, Circle, circle, Polyline, polyline, Polygon, polygon, Rectangle, rectangle, Map, createMap as map };
  11338. //# sourceMappingURL=leaflet-src.esm.js.map