TKems
TKems

Reputation: 109

Adding a square polygon of a set size around a point using leaflet.js

Bit of a weird one I hope someone can help out with.

In leaflet, once the user has entered a lat/lng and added a point to the map I want to be able to also add a 10km square around that point.

I've tried looking around for a calculation to find the corners of the square x Km away but haven't dug anything up. But surely there's an easier way!

Does anyone have any thoughts? It'd be lovely to just say L.polygon then pass in a centre point and a square size.

Thanks,

Tayler

Upvotes: 3

Views: 2726

Answers (2)

tbo47
tbo47

Reputation: 3299

Here is a example working with leaflet 1.9


    const perimeter = 100_000 // we want a rectangle with a 100km perimeter
    const rectangleCenter = [13, -13] // center of the rectangle
    const circle = L.circle(rectangleCenter, { radius: perimeter / 8 }).addTo(map)
    const { _northEast, _southWest } = circle.getBounds()
    map.removeLayer(circle)
    L.rectangle([[_northEast.lat, _northEast.lng], [_southWest.lat, _southWest.lng]], { color: "#ff7800", weight: 1 }).addTo(map)

Upvotes: 0

iH8
iH8

Reputation: 28638

Initialize a L.Circle on your desired latitude/longitude with a radius of 5000 meters, grab the boundaries and use them to initialize a L.Rectangle:

new L.Rectangle(new L.Circle([0, 0], 5000).getBounds())

Upvotes: 9

Related Questions