Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@neilkennedy
Last active April 10, 2021 10:39
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save neilkennedy/9227665 to your computer and use it in GitHub Desktop.
Save neilkennedy/9227665 to your computer and use it in GitHub Desktop.
Create a polygon from a Leaflet.js LatLngBounds object
/// <summary>
/// Takes an L.latLngBounds object and returns an 8 point L.polygon.
/// L.rectangle takes an L.latLngBounds object in its constructor but this only creates a polygon with 4 points.
/// This becomes an issue when you try and do spatial queries in SQL Server or another database because when the 4 point polygon is applied
/// to the curvature of the earth it loses it's "rectangular-ness".
/// The 8 point polygon returned from this method will keep it's shape a lot more.
/// </summary>
/// <param name="map">L.map object</param>
/// <returns type="">L.Polygon with 8 points starting in the bottom left and finishing in the center left</returns>
function createPolygonFromBounds(latLngBounds) {
var center = latLngBounds.getCenter()
latlngs = [];
latlngs.push(latLngBounds.getSouthWest());//bottom left
latlngs.push({ lat: latLngBounds.getSouth(), lng: center.lng });//bottom center
latlngs.push(latLngBounds.getSouthEast());//bottom right
latlngs.push({ lat: center.lat, lng: latLngBounds.getEast() });// center right
latlngs.push(latLngBounds.getNorthEast());//top right
latlngs.push({ lat: latLngBounds.getNorth(), lng: map.getCenter().lng });//top center
latlngs.push(latLngBounds.getNorthWest());//top left
latlngs.push({ lat: map.getCenter().lat, lng: latLngBounds.getWest() });//center left
return new L.polygon(latlngs);
}
@10n37
Copy link

10n37 commented Apr 9, 2021

does this work for any type of layer?

@neilkennedy
Copy link
Author

@RewriteH this is old code, so I have no idea if this is still valid for current versions of leaflet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment