Javascript 如何在 Leaflet.js 中更改地图中心
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12735303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the map center in Leaflet.js
提问by Joel James
The following code initializes a leaflet map. The initialize function centers the map based on user location. How do I change the center of the map to a new position after calling the initialize function?
以下代码初始化传单地图。初始化函数根据用户位置将地图居中。调用初始化函数后,如何将地图中心更改为新位置?
function initialize() {
map = L.map('map');
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery ?? <a href="http://cloudmade.com">CloudMade</a>'
}).addTo(map);
map.locate({setView: true, maxZoom: 8});
}
回答by Paulo Rodrigues
For example:
例如:
map.panTo(new L.LatLng(40.737, -73.923));
回答by Greg Wilson
You can also use:
您还可以使用:
map.setView(new L.LatLng(40.737, -73.923), 8);
It just depends on what behavior you want. map.panTo()
will pan to the location with zoom/pan animation, while map.setView()
immediately set the new view to the desired location/zoom level.
这仅取决于您想要什么行为。map.panTo()
将使用缩放/平移动画平移到该位置,同时map.setView()
立即将新视图设置为所需的位置/缩放级别。
回答by Stefan Nedelcu
Use map.panTo();
does not do anything if the point is in the current view. Use map.setView()
instead.
map.panTo();
如果点在当前视图中,则Use不会执行任何操作。使用map.setView()
来代替。
I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/
我有一条折线,我必须每秒将地图居中到折线中的一个新点。检查代码:好:https://jsfiddle.net/nstudor/xcmdwfjk/
mymap.setView(point, 11, { animation: true });
BAD: https://jsfiddle.net/nstudor/Lgahv905/
不好的:https: //jsfiddle.net/nstudor/Lgahv905/
mymap.panTo(point);
mymap.setZoom(11);
回答by Latinrickshaw
You could also use:
您还可以使用:
var latLon = L.latLng(40.737, -73.923);
var bounds = latLon.toBounds(500); // 500 = metres
map.panTo(latLon).fitBounds(bounds);
This will set the view level to fit the bounds in the map leaflet.
这将设置视图级别以适合地图传单中的边界。