我正在尝试在地图上设置一个按钮,允许用户缩放到他的位置。我正在使用Leaflet映射库(leaflet.cloudmade.com)。
locate()方法效果很好,但我想确保用户实际共享其位置,因为如果浏览器返回一个位置,我想让按钮改变。这是我一直在尝试使用的代码:
function locateUser() {
try {
this.map.locate({setView: true});
} catch(err) {
alert("Couldn't find your location.");
return false;
}
return true;
}
$("document").ready(function() {
var map = null;
initmap(); // This is the function that displays the map.
// Here is where I need to check whether the user was located.
// If he is located I want to switch the button to one that will
// reset the view.
var is_located = 0;
$("#myLocation").click(function() {
if (is_located == 0) {
if (locateUser()){
is_located = 1;
$(this).attr('value', 'WILMINGTON');
};
} else if (is_located == 1) {
$(this).attr('value', 'MY LOCATION');
is_located = 0;
};
});
});
传单文档说locate()方法返回一个locationfound事件或一个locationerror事件,但当我尝试记录locate()返回的内容时,我只是得到一个对象,我不清楚它是否找到用户的位置。
答案 0 :(得分:1)
Leaflet的locate()方法只返回Map对象,而不返回地理位置调用的状态。然而,在尝试地理定位后,Leaflet将触发两个事件中的一个:
我已在http://jsfiddle.net/XwbsU/5/
上传了一个使用这些事件的示例您可以看到我已经注册了这些事件,以确定地理位置调用是否成功。
希望有所帮助。