Skip to content

Instantly share code, notes, and snippets.

@jericopulvera
Forked from neilkennedy/polyFromBounds.js
Last active April 1, 2019 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jericopulvera/dc5f3a5e456bd9838feb57472feceb69 to your computer and use it in GitHub Desktop.
Save jericopulvera/dc5f3a5e456bd9838feb57472feceb69 to your computer and use it in GitHub Desktop.
[Leaflet LatLngBounds to Polygon]
/// <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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment