[GIS] Move leaflet polygon to given position

geolocationjavascriptleafletpolygon

I have a circle and a polygon that I'd like to move to the user's local position. I managed to move the circle latLng but I can't find a way to do the same thing with a polygon.

Can someone help me please?

Best Answer

You know that a circle in Leaflet is defined by a unique LatLng coordinate + radius, whereas a polygon is made of several LatLng coordinates.

That is why it is trivial to say "the circle is at this LatLng position". And it is trivial to center that circle on a user position.

But we are left with plenty options for the polygon: how should we compute its "position", since it is defined by many LatLng coordinates?

If your polygon is already defined around the [0, 0] position, then you could translate all its vertices (i.e. all its LatLng coordinates) by the user position.

Otherwise, you have to chose a "centre" (the most trivial would be the barycentre / centroid of its vertices), so that you can compute the difference with the user position, then translate all the polygon vertices like above by this difference.