Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all markers on Leaflet

Tags:

leaflet

I have a listener that will detect changes of the location of objects on databases. It will pass all the information of the object that is being changed.

I want to get all markers from the current map and find the marker that is affected. Once found, update the location.

But, I am still looking for the best ways to get all markers from the map and then I can update the location.

var map = L.map('map').setView([37.78541,-122.40787], 13);
var markers = new L.FeatureGroup();
var mapLink =
    '<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer(
    'https://{s}.tiles.mapbox.com/v4/examples.map-i87786ca/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZ2Vja29iIiwiYSI6IndzVjRGN0kifQ.lToORsjE0lkt-VQ2SXOb-Q', {
        attribution: '&copy; ' + mapLink + ' Contributors',
        maxZoom: 18,
    }).addTo(map);

var marker = createCircleMarker([44.977368, -93.232659]);
marker._id = "69"; // Id of the marker
map.addLayer(marker);
var socket = io();

socket.on('update location', function(obj) {
     // Get all markers and find markers with attribute obj.name to 
     // update the location to [obj.lat,obj.lon]

});
like image 677
geckob Avatar asked May 19 '15 06:05

geckob


People also ask

How many markers can Leaflet handle?

The Clusterer can handle 10,000 or even 50,000 markers (in chrome).

How do you add a marker in Leaflet?

Adding a Simple MarkerStep 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

Is Leaflet completely free?

Leaflet, unlike Google Maps and other all-in-one solutions, is just a JavaScript library. It's free to use, but doesn't provide map imagery on its own — you have to choose a tile service to combine with it.


2 Answers

Use eachLayer method on L.map. Like

map.eachLayer(function (layer) { 
    if (layer.options.name === 'XXXXX') {
        layer.setLatLng([newLat,newLon])
    } 
});

Documentation at http://leafletjs.com/reference-1.2.0.html#map-eachlayer

like image 101
snkashis Avatar answered Sep 16 '22 13:09

snkashis


To add an option without using map.eachLayer; all layers within the map are internally stored in map._layers.

Use

map._layers.forEach(function (layer) {
  ...
});

to iterate over ALL Layer elements. Not just the ones currently visible.

like image 22
nonNumericalFloat Avatar answered Sep 19 '22 13:09

nonNumericalFloat