Answers:
var group = new L.featureGroup([marker1, marker2, marker3]);
map.fitBounds(group.getBounds());
请参阅文档以获取更多信息。
markers.getBounds().pad(<percentage>)
如果您想将边界扩展给定的百分比,则可以使用,但也可以将padding选项传递给fitBounds,以设置像素的填充。markers.getBounds(), {padding: L.point(20, 20)})
由于某些原因,“答案”没有起作用。所以这就是我最终要做的事情:
////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!
LngLatLike
参数必须指定为LngLat实例,对象{lng:<lng>,lat:<lat>}或[<lng>,<lat>]的数组。任何想法?
Leaflet也具有LatLngBounds,甚至具有扩展功能,就像google maps一样。
http://leafletjs.com/reference.html#latlngbounds
因此,您可以简单地使用:
var latlngbounds = new L.latLngBounds();
其余的完全一样。
对于Leaflet,我正在使用
map.setView(markersLayer.getBounds().getCenter());
您还可以找到一个FeatureGroup或所有FeatureGroup中的所有要素,看看它是如何工作的!
//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>
为了只适合可见标记,我有此方法。
fitMapBounds() {
// Get all visible Markers
const visibleMarkers = [];
this.map.eachLayer(function (layer) {
if (layer instanceof L.Marker) {
visibleMarkers.push(layer);
}
});
// Ensure there's at least one visible Marker
if (visibleMarkers.length > 0) {
// Create bounds from first Marker then extend it with the rest
const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
visibleMarkers.forEach((marker) => {
markersBounds.extend(marker.getLatLng());
});
// Fit the map with the visible markers bounds
this.map.flyToBounds(markersBounds, {
padding: L.point(36, 36), animate: true,
});
}
}