Gan*_*rry 4 openstreetmap fitbounds leaflet
我正在将我的网站从谷歌地图转换为传单/openstreetmap。在网站上,搜索结果在地图上显示为标记。结果可以有一个标记,或 10 或 200。这一切都很好。但是当结果有多个标记时,我很难让它缩放/适合所有标记。相反,它只是放大一个(可能是因为我将 map.setView 放大到 18!)。
就我而言,是否有使用 map.setView 的替代方法?我不想在所有情况下都将缩放设置为 18;但希望缩放只适合内容。我知道 SO 上有一些类似的问题,但它们无济于事,因为我不知道如何用 map.setView 替换一些不硬编码缩放的东西。这是我的整个功能:
function showLocations(ids, lats, lons, contents) {
locationIDs = ids;
infoWindows = new Array();
markers = new Array();
map = new L.Map('map_canvas');
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 1, maxZoom: 19, attribution: osmAttrib});
for (i in ids) {
var infoWindow = L.popup()
.setContent(contents[i]);
map.setView(new L.LatLng(lats[i], lons[i]),18);
map.addLayer(osm);
L.marker([lats[i], lons[i]]).addTo(map)
.bindPopup(infoWindow)
.openPopup();
}
}
Run Code Online (Sandbox Code Playgroud)
使用谷歌地图,我使用这个:
markers.push(marker);
bounds.extend(latlng);
if (contents.length === 1) {
map.setZoom(18);
map.setCenter(new google.maps.LatLng(lats[0], lons[0]));
} else {
map.fitBounds(bounds);
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Leaflet 也有一个LatLngBounds类,有一个extend方法,地图有一个fitBounds方法,所以你可以 1:1 移植谷歌地图代码。
再补充几点:map.addLayer(osm)循环内部不需要调用,调用一次就够了;添加var到所有变量中是一种很好的做法;并且for (i in ids)是迭代数组的危险方式,最好调用ids.forEach.
function showLocations(ids, lats, lons, contents) {
var infoWindows = new Array();
var markers = new Array();
var map = new L.Map('map_canvas');
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 1, maxZoom: 19, attribution: osmAttrib});
map.addLayer(osm);
var bounds = new L.LatLngBounds();
ids.forEach(function(i) {
var infoWindow = L.popup().setContent(contents[i]);
var marker = L.marker([lats[i], lons[i]])
.addTo(map)
.bindPopup(infoWindow)
.openPopup();
bounds.extend(marker.getLatLng());
});
map.fitBounds(bounds);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3751 次 |
| 最近记录: |