最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Finding a marker by option value - Stack Overflow

programmeradmin1浏览0评论

Let's say that you have a Leaflet map, with a set of custom markers, and each marker has a unique id value:

var marker = new L.marker(latlong, {id: id, icon: icon}).addTo(map);

What's the remended way to access a marker (specifically, I'd like to modify a marker's class), by its 'id' value?

Let's say that you have a Leaflet map, with a set of custom markers, and each marker has a unique id value:

var marker = new L.marker(latlong, {id: id, icon: icon}).addTo(map);

What's the remended way to access a marker (specifically, I'd like to modify a marker's class), by its 'id' value?

Share Improve this question asked Jun 21, 2017 at 17:49 BoaBoa 2,6971 gold badge25 silver badges39 bronze badges 1
  • note: you can/should (perhaps this was amended in most recent versions of Leaflet) use "uniqueID" instead – Razvan_TK9692 Commented Feb 29, 2020 at 7:27
Add a ment  | 

2 Answers 2

Reset to default 7

Iterate all the map's layer, check if it's a marker and pare the id's:

L.Map.include({
    getMarkerById: function (id) {
        var marker = null;
        this.eachLayer(function (layer) {
            if (layer instanceof L.Marker) {
                if (layer.options.id === id) {
                    marker = layer;
                }
            }
        });
        return marker;
    }
});

var map = new L.Map(...);

var marker = new L.Marker(..., {id: 1});

map.getMarkerById(1); // returns marker instance
map.getMarkerById(2); // returns null

Instead of looping through all markers, I'd suggest keeping a dictionary of markers, using their ID as the key, e.g.:

var markers = {};

markers[id] = new L.marker(latlong, {id: id, icon: icon}).addTo(map);

Then you simply refer to marker[id].

A more plicated example:

var markers = {};
var data = [ ['alpha', 0, -80],
             ['beta',  20, 35],
             ['delta', -70, 44],
           ];

data.forEach(function(item){
    var id = item[0];
    var latLng = L.latLng(item[1], item[2]);
    markers[id] = new L.marker(latLng, {id: id, icon: icon}).addTo(map);
});

console.log(markers['delta']); // returns the marker at -70, 44
发布评论

评论列表(0)

  1. 暂无评论