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

center of a polygon created with mapbox

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

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

Returns the LatLngBounds of the polyline.

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

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

Returns the center point of the bounds

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

它 returns 一个 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);

或者你可以shorthand它:

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

var marker = new L.Marker(polygon.getBounds().getCenter()).addTo(map);

在 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();
}

您可以使用 turf library.turf.center(features) 在所有输入要素的绝对中心点为您提供一个点要素。您的案例中的要素将是您可以使用 mapboxDraw.getAll()

获得的所选多边形