MapboxやLeaflet**で地図上のすべてのマーカーを表示するにはどうすればよいですか?Google Maps API が bounds
で行うように?
例
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);
LeafletにもLatLngBoundsがあり、google mapのようにextend機能まであります。
http://leafletjs.com/reference.html#latlngbounds
なので、単純に
var latlngbounds = new L.latLngBounds();
あとは exactly と同じです。
また、FeatureGroupまたはすべてのfeatureGroups内のすべての機能を見つけることができます。 それがどのように機能するかを参照してください。!
<。!-スニペットを開始:js hide:false console:true babel:false -->。
//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/[email protected]/dist/leaflet.js"></script>
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>
<div id="map" class="mymap"></div>
<button onclick="LocateOne()">locate group 1</button>
<button onclick="LocateAll()">locate All</button>
<。!-終了スニペット-->。
最良の方法は、次のコードを使用することです。
var group = new L.featureGroup([marker1, marker2, marker3]);
map.fitBounds(group.getBounds());