ShadowRock
ShadowRock

Reputation: 105

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

Upvotes: 1

Views: 3520

Answers (1)

IvanSanchez
IvanSanchez

Reputation: 19099

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.LayerGroups, e.g.

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 LayerGroups separately, e.g.

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:

Upvotes: 1

Related Questions