我的解决方案没有明确使用map.locate。这是不需要的,因为 map.locate 是通过添加 leaflet-geolocation 元素启用的。
我从 leaflet-map 元素中删除了纬度和经度属性(并添加了一些其他参数):
<leaflet-map
id="nycmap" zoom="14"
min-zoom="14"
max-zoom="18"
nozoomControl="true"
noattributionControl:="false">
然后,我向 leaflet-map 元素 (leaflet-core.html) 的注册添加了一个一次性监听器,这样,如果启用了地理定位,地图将缩放到该位置,如果未启用,它将缩放到默认中心点。 “geoB”是一个切换地理定位功能的按钮:
map.addOneTimeEventListener('locationfound', function (e){
console.log("get to located found?");
map.setView(L.latLng(e.latitude, e.longitude), 14);
var geo = document.getElementById('geoB');
var state = geo.classList.toggle('toggleState');
}, this);
map.on('locationerror', function(e){
console.log("get to located error?");
map.setView(L.latLng(40.6889, -73.9444), 14);
map.stopLocate();
}, this);
我向 leaflet-map 元素添加了另一个函数,以便我可以将当前的纬度和经度传递给该元素,并在单击地理位置按钮时缩放到该点:
setToPoint: function(newLat, newLong){
if (this.map && !this._ignoreViewChange) {
this.async(function() {
this.map.setView(L.latLng(newLat, newLong), this.zoom, {pan: {animate: true}});
this.map.invalidateSize();
});
}
},
最后,在 geoButton 元素的事件监听器中调用此函数,该元素引用 leaflet-geolocation 元素:
nycmap.setToPoint(locator.latitude, locator.longitude);