I have a leaflet JS map that displays data from a GeoJSON file. However some of the features in the geojson are polygons, and some are points. I would like to replace each polygon with a point (in the centroid, in the average of the bbox, whatever, it doesn't matter, the accuracy isn't that important), so that I can "point-ify" the whole geojson file, and just display one leaflet marker for each point, or polygon-that-was-turned-into-a-point. I don't want to display the outline of the polygons.
You could use the onEachFeature
option of the L.GeoJSON
layer, it takes a function which is run for each feature in your featurecollection. In there you can differentiate between points and polygons. A quick example:
var map = L.map('map', {
center: [0, 0],
zoom: 0
});
var geoJsonLayer = L.geoJson(featureCollection, {
onEachFeature: function (feature, layer) {
// Check if feature is a polygon
if (feature.geometry.type === 'Polygon') {
// Don't stroke and do opaque fill
layer.setStyle({
'weight': 0,
'fillOpacity': 0
});
// Get bounds of polygon
var bounds = layer.getBounds();
// Get center of bounds
var center = bounds.getCenter();
// Use center to put marker on map
var marker = L.marker(center).addTo(map);
}
}
}).addTo(map);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With