Leaflet: Including metadata with CircleMarkers

后端 未结 2 889
心在旅途
心在旅途 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:16

    FWIW, you have plenty ways of adding your own data to Leaflet Layers (nothing specific to Circle Markers, it is the same for Markers, but also Polygons, Polylines, etc.).

    See for instance: Leaflet/Leaflet #5629 (Attach business data to layers)

    In short, there are mainly 3 possible ways:

    • Just directly add some properties to the Leaflet Layer after it has been instantiated. Make sure you avoid collision with library properties and methods. You can add your own prefix to the property name to decrease the chance of collision.
    var marker = L.marker(latlng);
    marker.myLibTitle = 'my title';
    
    • Use the Layer options (usually the 2nd argument of the instantiation factory), as shown by @nikoshr. As previously, avoid collision with library option names.
    L.marker(latlng, {
      myLibTitle: 'my title'
    });
    
    • Use the Layer GeoJSON properties. Leaflet does not use those for internal purpose, so you have total freedom of this data, without any risk of collision.
    L.Layer.include({
      getProps: function () {
        var feature = this.feature = this.feature || {}; // Initialize the feature, if missing.
        feature.type = 'Feature';
        feature.properties = feature.properties || {}; // Initialize the properties, if missing.
        return feature.properties;
      }
    });
    
    var marker = L.marker(latlng);
    
    // set data
    marker.getProps().myData = 'myValue';
    
    // get data
    myFeatureGroup.on('click', function (event) {
      var source = event.sourceTarget;
      console.log(source.getProps().myData);
    });
    

提交回复
热议问题