Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

leaflet how to setView according to multiple point

Tags:

leaflet

The setView() function accept a center coordinate and . I've fetch bunch of points from Google place API, and I want to set the view to include those point in the view.

I've calculated a appropriate bounding box (int lat and lng), but no idea how to set the view aligned with lat and lng, as the setView() only accept center coordinate and zoom, the zoom seems to be measured in pixel

like image 412
Ziqi Liu Avatar asked Nov 16 '17 07:11

Ziqi Liu


1 Answers

Use map.fitBounds():

Sets a map view that contains the given geographical bounds with the maximum zoom level possible.

Additionally, you can automatically compute the appropriate bounding box of your POI's using a Feature Group then group.getBounds():

Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).

var map = L.map("map").setView([48.85, 2.35], 10);

var markers = [
  L.marker([48.84, 2.34]),
  L.marker([48.85, 2.35]),
  L.marker([48.86, 2.36])
];

var group = L.featureGroup(markers).addTo(map);

setTimeout(function () {
  map.fitBounds(group.getBounds());
}, 1000);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js"></script>

<div id="map" style="height: 200px;"></div>
like image 168
ghybs Avatar answered Nov 07 '22 15:11

ghybs