Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a marker for polygons from a GeoJSON file in Leaflet

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.

like image 539
Amandasaurus Avatar asked Dec 11 '22 01:12

Amandasaurus


1 Answers

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);
like image 147
iH8 Avatar answered Jan 12 '23 00:01

iH8