Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if leaflet map is zoomed in or zoomed out?

Leaflet has the events 'zoomstart' and 'zoomend', but I want to know if the map is zoomed in or zoomed out, after the zoom event.

edit1:

I have added a fiddle, but this dosen't work correctly: http://jsfiddle.net/LnzN2/1940/

var prevZoom = map.getZoom();

map.on('zoomstart',function(e){
  debugger;
  var currZoom = map.getZoom();
  var diff = prevZoom - currZoom;
  if(diff > 0){
    alert('zoomed in');
  } else if(diff < 0) {
    alert('zoomed out');
  } else {
    alert('no change');
  }
  prevZoom = currZoom;
});
like image 270
Neelotpal Avatar asked Mar 07 '18 05:03

Neelotpal


People also ask

How do you get a zoom level on a leaflet map?

In react You can get zoomLevel by using getZoom method() and using useRef.

How do you remove zoom control in leaflet?

You can remove the default zoom control by setting the zoomControl option of the map options to false.

What is zoom level?

A zoom level or scale is a number that defines how large or small the contents of a map appear in a map view . Scale is a ratio between measurements on a map view and measurements in the real-world.


1 Answers

Just change the zoomstart to zoomend as the library updates the levels after zooming is done.

Also when the value is -1 it reduces the zoom level therefor it means you've zoomed in, but you had it the other way around.

Changed all that and seems to me that fixed the issue. Check snippet below. And here is the updated fiddle http://jsfiddle.net/LnzN2/1965/

// We’ll add a tile layer to add to our map, in this case it’s a OSM tile layer.
// Creating a tile layer usually involves setting the URL template for the tile images
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
osm = L.tileLayer(osmUrl, {
	   maxZoom: 18,
	   attribution: osmAttrib
});

// initialize the map on the "map" div with a given center and zoom
var map = L.map('map').setView([0,0], 2).addLayer(osm);
var prevZoom = map.getZoom();
    
map.on('zoomend',function(e){
	debugger;
	var currZoom = map.getZoom();
    var diff = prevZoom - currZoom;
    if(diff > 0){
  	   alert('zoomed out');
    } else if(diff < 0) {
  	   alert('zoomed in');
    } else {
  	   alert('no change');
    }
    prevZoom = currZoom;
});
#map {
    height: 500px;
    width: 80%;
}
<link href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" rel="stylesheet"/>
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="map"></div>
like image 106
richardev Avatar answered Sep 29 '22 20:09

richardev