Zoom to fit all markers in Mapbox or Leaflet

2019-01-16 05:28发布

How do I set view to see all markers on map in Mapbox or Leaflet? Like Google Maps API does with bounds?

E.g:

var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
  latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);

6条回答
可以哭但决不认输i
2楼-- · 2019-01-16 05:39

The 'Answer' didn't work for me some reasons. So here is what I ended up doing:

////var group = new L.featureGroup(markerArray);//getting 'getBounds() not a function error.
////map.fitBounds(group.getBounds());
var bounds = L.latLngBounds(markerArray);
map.fitBounds(bounds);//works!
查看更多
Bombasti
3楼-- · 2019-01-16 05:44
var markerArray = [];
markerArray.push(L.marker([51.505, -0.09]));
...
var group = L.featureGroup(markerArray).addTo(map);
map.fitBounds(group.getBounds());
查看更多
淡お忘
4楼-- · 2019-01-16 05:53

Leaflet also has LatLngBounds that even has an extend function, just like google maps.

http://leafletjs.com/reference.html#latlngbounds

So you could simply use:

var latlngbounds = new L.latLngBounds();

The rest is exactly the same.

查看更多
冷血范
5楼-- · 2019-01-16 05:55
var group = new L.featureGroup([marker1, marker2, marker3]);

map.fitBounds(group.getBounds());

See the documetation for more info.

查看更多
老娘就宠你
6楼-- · 2019-01-16 06:04

For Leaflet, I'm using

    map.setView(markersLayer.getBounds().getCenter());
查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-16 06:05

You also can locate all features inside a FeatureGroup or all the featureGroups, see how it works!

//Group1
m1=L.marker([7.11, -70.11]);
m2=L.marker([7.33, -70.33]);
m3=L.marker([7.55, -70.55]);
fg1=L.featureGroup([m1,m2,m3]);

//Group2
m4=L.marker([3.11, -75.11]);
m5=L.marker([3.33, -75.33]);
m6=L.marker([3.55, -75.55]);
fg2=L.featureGroup([m4,m5,m6]);

//BaseMap
baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
var map = L.map('map', {
  center: [3, -70],
  zoom: 4,
  layers: [baseLayer, fg1, fg2]
});

//locate group 1
function LocateOne() {
    LocateAllFeatures(map, fg1);
}

function LocateAll() {
    LocateAllFeatures(map, [fg1,fg2]);
}

//Locate the features
function LocateAllFeatures(iobMap, iobFeatureGroup) {
		if(Array.isArray(iobFeatureGroup)){			
			var obBounds = L.latLngBounds();
			for (var i = 0; i < iobFeatureGroup.length; i++) {
				obBounds.extend(iobFeatureGroup[i].getBounds());
			}
			iobMap.fitBounds(obBounds);			
		} else {
			iobMap.fitBounds(iobFeatureGroup.getBounds());
		}
}
.mymap{
  height: 300px;
  width: 100%;
}
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" rel="stylesheet"/>

<div id="map" class="mymap"></div>
<button onclick="LocateOne()">locate group 1</button>
<button onclick="LocateAll()">locate All</button>

查看更多
登录 后发表回答