Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a circle of constant size for all zoom levels leaflet.js

I am trying to implement something like this using leaflet.js, where the size of the circle remains the same on varying zoom levels. For example, if I want to depict the populations in different US counties, I would have circles of different radius represent different ranges of populations. They may overlap when zoomed out completely, but once we start zooming in, they tend to separate. So is there a way to do this using leaflet.js. I saw an issue raised, but I wasn't able to follow if it was fixed or not. Any help would be deeply appreciated.

like image 478
aa8y Avatar asked Mar 17 '14 23:03

aa8y


People also ask

How to set zoom level in leaflet?

A leaflet map has several ways to control the zoom level shown, but the most obvious one is setZoom() . For example, map. setZoom(0); will set the zoom level of map to 0 .

How to zoom in leaflet?

Zoom − By default, this control exists at the top left corner of the map. It has two buttons "+" and "–", using which you can zoom-in or zoom-out the map. You can remove the default zoom control by setting the zoomControl option of the map options to false.


2 Answers

For circles, just use circleMarker instead of circle: http://leafletjs.com/reference.html#circlemarker

like image 123
Aaron Schumacher Avatar answered Sep 17 '22 01:09

Aaron Schumacher


I think you're gonna want to do something like this:

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

var circle = L.circle([51.508, -0.11], 500, {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5
}).addTo(map);

var myZoom = {
  start:  map.getZoom(),
  end: map.getZoom()
};

map.on('zoomstart', function(e) {
   myZoom.start = map.getZoom();
});

map.on('zoomend', function(e) {
    myZoom.end = map.getZoom();
    var diff = myZoom.start - myZoom.end;
    if (diff > 0) {
        circle.setRadius(circle.getRadius() * 2);
    } else if (diff < 0) {
        circle.setRadius(circle.getRadius() / 2);
    }
});

What I've done is simply initialize a map and a circle and created event listeners for the zoomstart and zoomend events. There's a myZoom object that records the zoom levels so you can find out whether or not the final zoom is in or out by simple subtraction. In the zoomEnd listener, you check that and change the circle radius based on whether the difference is greater or lesser than 0. We of course do nothing when it's 0. This is where I leave you to get more sophisticated with your results. But, I think this demonstrates how to do it.

like image 37
4m1r Avatar answered Sep 19 '22 01:09

4m1r