0
我正在尋找一種方法來觸發用戶地理位置導航功能從另一個功能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);
}
'getCurrentPosition()'似乎會返回,然後像W3C在API規範中寫的那樣異步獲取用戶位置:「調用時,它必須立即返回,然後異步地嘗試獲取設備的當前位置。 [(源)](http://dev.w3.org/geo/api/spec-source.html#geolocation)。有人有線索嗎? – Antoine 2012-08-10 12:10:26