简体   繁体   中英

How to add a marker to the middle of a polygon in leaflet?

I want to add a marker in the middle of a polygon that is made form geojson data. The polygon is connected a control where the layer can be turned on and off. This marker should only be displayed when the layer is active. I have the following code:

var geoJsonLayer = L.geoJSON(Locations, {
  onEachFeature: function (feature, layer) {
    if (feature.geometry.type === "Polygon") {
      var bounds = layer.getBounds();
      var center = bounds.getCenter();

      var markerTitle = feature.properties.ItemId;
      layer.id = markerTitle;

      var popUpFormat = dataPopUp(feature);
      layer.bindPopup(popUpFormat, customPopUpOptions);
    }
  },
});

Thanks for your interest and I hope someone can help me:D

You want to group a L.Polygon and a L.Marker together, and treat them as the same entity. This is a textbook scenario for using L.LayerGroup s, eg

var geoJsonLayer = L.geoJSON(Locations, {
  onEachFeature: function (feature, layer) {
    if (feature.geometry.type === "Polygon") {
      var center = layer.getBounds().getCenter();
      var marker = L.marker(center);
      var polygonAndItsCenter = L.layerGroup([layer, marker]);
    }
  },
});

Now polygonAndItsCenter is a L.LayerGroup with the polygon and its center (so adding/removing to/from the map will apply to both), but geoJsonLayer will contain only the polygons. How you handle that is up to you, but I guess you might want to not add geoJson to the map (using only for parsing and instantiating the polygons), and keep track of your polygon+marker LayerGroup s separately, eg

var polygonsWithCenters = L.layerGroup();

var geoJsonLayer = L.geoJSON(Locations, {
  onEachFeature: function (feature, layer) {
    if (feature.geometry.type === "Polygon") {
      var center = layer.getBounds().getCenter();
      var marker = L.marker(center);
      var polygonAndItsCenter = L.layerGroup([layer, marker]);
      polygonAndItsCenter.addTo(polygonsWithCenters);
    }
  },
});

// geoJsonLayer.addTo(map);  // No!!
polygonsWithCenters.addTo(map);

// Do something with a polygon+marker, e.g. remove the first one from the map
polygonsWithCenters.getLayers()[0].remove();

There are a few secondary problems that can spawn for this, so think about what you want to do with each polygon/layergroup/marker before writing code, keep the Leaflet documentation at hand, and remember:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM