我正在寻找一种从另一个函数mapInit()
触发用户地理位置导航功能的方法。它几乎可以工作,但我无法正确回调getCurrentPosition()
以确认它进展顺利..它每次都返回undefined。
我的地理定位对象必须完成其他任务,所以我不希望它触发mapInit()
。它应该获取用户位置,记录并返回true
或false
..有什么猜测?
谢谢:)
// Get user current position, return true or false
//
var geolocation = {
get: function() {
if (alert(navigator.geolocation.getCurrentPosition(this.success, this.error, {
enableHighAccuracy: true,
maximumAge: 5000
})) {
return true;
} else {
return false;
}
},
success: function(position) {
this.last = position; // record last position
return true;
},
error: function() {
alert('code: ' + error.code + 'n' + 'message: ' + error.message + 'n')
return false;
},
last: undefined,
}
// Initialize leaflet map and get user location if coords are undefined
//
var mapInit = function(latitude, longitude) {
if (!latitude && !longitude) { // if no latlng is specified, try to get user coords
if (geolocation.get()) {
latitude = geolocation.last.coords.latitude;
longitude = geolocation.last.coords.longitude;
} else {
alert('oups!');
}
}
var map = L.map('map').setView([latitude, longitude], 15);
L.tileLayer('http://{s}.tile.cloudmade.com/#APIKEY#/68183/256/{z}/{x}/{y}.png', {
minZoom: 13,
maxZoom: 16,
}).addTo(map);
var marker = L.marker([latitude, longitude]).addTo(map);
}
答案 0 :(得分:1)
我不确定你是否理解你要做的事情但是当你调用“getCurrentPosition”时,你传递的第一个参数是一个方法,一旦它被检索就会被调用。正如您在评论中所说,getCurrentPosition将始终立即返回,但如果可以检索用户位置(可能永远不会被调用),则将调用回调方法:
navigator.geolocation.getCurrentPosition( function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
//do something like recent the Map
});
您需要首先使用一些默认坐标创建Leaflet Map,然后使用提供给回调方法的坐标重新定位地图。