Surfget
Surfget

Reputation: 73

center of a polygon created with mapbox

I would like to know how to calculate the centre of a polygon created with this code from Mapbox: https://www.mapbox.com/mapbox.js/example/v1.0.0/show-polygon-area/ I would like to place a marker on the centre of the polygon after it's been created. Thanks in advance.

Upvotes: 5

Views: 14079

Answers (2)

Kartik Malhotra
Kartik Malhotra

Reputation: 257

You can use turf library.turf.center(features) gives you a point feature at the absolute center point of all input features. where features in your case will be the polygon selected which you can get using mapboxDraw.getAll()

Upvotes: 2

iH8
iH8

Reputation: 28628

To calculate the center of a polygon you first need to get it's bounds, that can be done using the getBounds method of L.Polygon which it enherits from L.Polyline:

Returns the LatLngBounds of the polyline.

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

It returns a L.LatLngBounds object which has a getCenter method:

Returns the center point of the bounds

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

It returns a L.LatLng object which you can use to create a 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);

Or you can shorthand it:

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

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

Using that in the Mapbox example would look something like this:

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

Upvotes: 6

Related Questions