How to create LatLngBounds around a LatLng point with a distance in meters?

I would like to create a square (LatLngBounds) around a center point (LatLng) at X meters.

+4
source share
2 answers

Use a method L.LatLng.toBounds()like

var center = L.latLng(40,-3);
var bounds = center.toBounds(500);

or

var bounds = L.latLng(40,-3).toBounds(500)
+6
source

The following solution demonstrates how to draw such a square:

  • calculate borders by drawing a circle at a point with a specified radius in meters
  • draw a square using the borders of the circle

Example

function drawSquare(map, center, properties, sideLengthInMeters){
    var circle = L.circle(center, sideLengthInMeters/2).addTo(map);   
    var bounds = circle.getBounds();
    map.removeLayer(circle); //hide circle
    var rect = L.rectangle(bounds, properties).addTo(map);
    return rect;
}

Demo

var center = [59.33,18.02];

// Create the map
var map = L.map('map').setView(center, 10);

// Set up the OSM layer
L.tileLayer(
        'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        { maxZoom: 18 }).addTo(map);

    
L.marker(center).addTo(map);

var sideInMeters = 10000;
drawSquare(map,center,{ color: 'blue', weight: 1 }, sideInMeters);


function drawSquare(map, center, properties, sideLengthInMeters){
    var circle = L.circle(center, sideLengthInMeters/2).addTo(map);   
    var bounds = circle.getBounds();
    map.removeLayer(circle); //hide circle
    var rect = L.rectangle(bounds, properties).addTo(map);
    return rect;
}
#map { 
    height: 400px; 
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.0.1/dist/leaflet.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="app.js"></script>
<div id="map"></div>
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1659043/


All Articles