3
votes

I am using leaflet js to draw a map. I am struggling in situation where i want to get latitude, longitude & zoom level of map on two events first is zoom and second in on click. I have search a stack's post : Get Position on zooming in map : leaflet but no help is found. At first i have tried to get lat & lng first but i get southwest & northeast meta data how can i get a perfect lat & lng.

var map = L.map('map').setView([51.505, -0.09], 13);

var tiles = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}.png', {
		maxZoom: 18,
		attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
	    }).addTo(map);

// first i try the on zoomend event to get lat, lng
map.on('zoomend',function(e){
    var map = e.target,
    bounds = map.getBounds();
    // here i get southwest & northeast data how to get lat & lng & zoom level 
   console.log(bounds);	
})
<!-- required js & css -->
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />

<!-- in it i draw map -->
<div id="map" style="height:400px; width:900px"></div>
2

2 Answers

1
votes

In order to get coordinates you need to target a point or a place. You can't get coordinates when zooming because it is just an area. You will get the boundaries of the area.

When clicking on the map listen to click event [docs] in order to retrieve the coordinates of the place on the map you just clicked (https://leafletjs.com/reference-1.3.4.html#map-mouseeventtolatlng):

map.on('click', function(ev){
  var coordinates = map.mouseEventToLatLng(ev.originalEvent);
  console.log(coordinates.lat + ', ' + coordinates.lng);
});

To get zoom on a zoom event you need to call:

map.on('zoomend',function(e) {
   console.log(e.target.getZoom());
})

Demo

0
votes

getCenter() will get you the lat/lng at the center of the map and getZoom() will get you the zoom level.

map.on('zoomend',function(e) {
   console.log(e.target.getCenter());
   console.log(e.target.getZoom());
})