Reputation: 8130
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: '© ' + 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]
});
Upvotes: 11
Views: 29254
Reputation: 1594
You can go through the DOM elements (image icons, marker-clusters, etc.) and get the hidden leaflet ID that is undocumentedly attached to it. Select it in the [ DevTools › Elements ] panel and enter $0._leaflet_id
or console.dir($0)
to see for yourself.
Use that ID to reference the object version of that element in your map leaflet object: leaflet_object = map._targets[leafletId]
.
Try if that works for you.
If you have marker clusters, you might have to go through each layer and get all those hidden child markers.
Using jQuery:
$('.marker-cluster').each((index, el) => {
let markers = map._targets?.[el._leaflet_id]?.getAllChildMarkers() ?? [];
// … do something with those markers
});
Upvotes: 0
Reputation: 1787
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.
Upvotes: 3
Reputation: 2991
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
Upvotes: 22