Get Current position on ZoomStart

2019-07-25 14:27发布

问题:

I am using leaflet to display a map.

This is my head code :

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.2/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.0.2/dist/leaflet.js"></script>

and this is my body code :

<div id="mapid" style="height: 1000px">&nbsp;</div>
<script>
    var mymap = L.map('mapid').setView([51.505, -0.09], 13);
    L.tileLayer('https://b.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
        maxZoom: 18,
        minZoom: 3
    }).addTo(mymap);

    mymap.on('click', function (e) { alert(e.latlng); });
    mymap.on('zoomstart', function (e) { alert(e.latlng); });
</script>

This map has two events as you can see from the code above : on click event and on zoomstart event.

When I click on the map I got the popup alert : LatLng(51.51600,-1.54213).

But when I zoom on the map I got the popup alert : undefined.

How can I get the current position on zoomstart Event ?

回答1:

In Leaflet, the events for map state change do not have a latlng property.

Read the documentation, and notice the difference between the zoomstart/zoomend/etc events...

http://leafletjs.com/reference-1.0.2.html#map-map-state-change-events

...and the events generated by user interaction, such as click:

http://leafletjs.com/reference-1.0.2.html#map-interaction-events

Depending on the event type, some information is or is not available. In most cases, events have the information that makes sense for them.

If you want to know the map's center latlng when a zoom operation starts, simply use mymap.getCenter() inside the event handler.