首页 文章

从Leaflet中的GeoJSON文件显示多边形的标记

提问于
浏览
2

我有一个传单JS Map ,显示GeoJSON文件中的数据 . 然而,geojson中的一些特征是多边形,有些是点 . 我想用一个点替换每个多边形(在质心中,在bbox的平均值中,无论如何,无关紧要,准确性并不重要),这样我就可以“指出 - 整个” geojson文件,只显示每个点的一个传单标记,或者那个被转换为点的多边形 . 我不想显示多边形的轮廓 .

1 回答

  • 10

    您可以使用 L.GeoJSON 图层的 onEachFeature 选项,它会为您的featurecollection中的每个要素运行一个函数 . 在那里,您可以区分点和多边形 . 一个简单的例子:

    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);
    

相关问题