Leaflet: Including metadata with CircleMarkers

后端 未结 2 915
心在旅途
心在旅途 2021-01-19 15:30

I have a Leaflet map that I am populating with CircleMarkers. I would like to include an additional value (a database ID) with each circle so that when I click on the circle

2条回答
  •  情深已故
    2021-01-19 16:14

    • Events fired on members of a FeatureGroup are propagated to the FeatureGroup object
    • Event objects expose a sourceTarget member giving you access to the source marker
    • Options in a layer can be accessed as marker.options

    From there, you could pass your id as a member of the options object when building your markers and retrieve this value when a marker is clicked. For example:

    var points = data.map((datum) => {
        return L.circleMarker(datum, {radius: 5, id: datum.id});
    });
    
    var group = L.featureGroup(points);
    group.addTo(map);
    
    group.on("click", (e) => {
        console.log(e.sourceTarget.options.id);
    });
    

    And a demo

    var data = [
    	{lat: 20.45, lng: -150.2, id: 44},
    	{lat: 23.45, lng: -151.7, id: 45},
    ]
    var points = [];
    
    var map = L.map('map', {
        center: [20.45, -150.2],
        zoom: 4
    });
    
    var points = data.map(function (datum) {
        return L.circleMarker(datum, {radius: 5, id: datum.id});
    });
    
    var group = L.featureGroup(points);
    group.addTo(map);
    
    group.on("click", function (e) {
        console.log(e.sourceTarget.options.id);
    });
    html, body {
      height: 100%;
      margin: 0;
    }
    #map {
      width: 100%;
      height: 150px;
    }
    
    
    
    

提交回复
热议问题