使用mapbox创建的多边形的中心

Sur*_*get 3 javascript polygon mapbox

我想知道如何计算使用 Mapbox 中的此代码创建的多边形的中心: https: //www.mapbox.com/mapbox.js/example/v1.0.0/show-polygon-area/ 我想创建多边形后,在其中心放置一个标记。提前致谢。

iH8*_*iH8 5

要计算多边形的中心,您首先需要获取它的边界,这可以使用它继承的getBounds方法来完成:L.PolygonL.Polyline

返回折线的 LatLngBounds。

http://leafletjs.com/reference.html#polyline-getbounds

它返回一个L.LatLngBounds具有getCenter方法的对象:

返回边界的中心点

http://leafletjs.com/reference.html#latlngbounds-getcenter

它返回一个L.LatLng可用于创建的对象L.Marker

var polygon = new L.Polygon(coordinates).addTo(map);

var bounds = polygon.getBounds();

var center = bounds.getCenter();

var marker = new L.Marker(center).addTo(map);
Run Code Online (Sandbox Code Playgroud)

或者你可以简写它:

var polygon = new L.Polygon(coordinates).addTo(map);

var marker = new L.Marker(polygon.getBounds().getCenter()).addTo(map);
Run Code Online (Sandbox Code Playgroud)

在 Mapbox 示例中使用它看起来像这样:

function showPolygonArea(e) {
    featureGroup.clearLayers();
    featureGroup.addLayer(e.layer);

    // Here 'e.layer' holds the L.Polygon instance:
    new L.Marker(e.layer.getBounds().getCenter()).addTo(featureGroup);

    e.layer.bindPopup((LGeo.area(e.layer) / 1000000).toFixed(2) + ' km<sup>2</sup>');
    e.layer.openPopup();
}
Run Code Online (Sandbox Code Playgroud)