2012-08-10 50 views
0

我正在尋找一種方法來觸發用戶地理位置導航功能從另一個功能mapInit()。它幾乎可以工作,但我不能有一個適當的回調getCurrentPosition(),以確認它進展順利..它每次都返回undefined。地理位置無法返回確認?

我的地理定位對象將不得不實現其他任務,所以我不希望它觸發mapInit()。它應該得到用戶位置,記錄它並返回truefalse ..任何猜測?

謝謝:)

// 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

'getCurrentPosition()'似乎會返回,然後像W3C在API規範中寫的那樣異步獲取用戶位置:「調用時,它必須立即返回,然後異步地嘗試獲取設備的當前位置。 [(源)](http://dev.w3.org/geo/api/spec-source.html#geolocation)。有人有線索嗎? – Antoine 2012-08-10 12:10:26

回答

1

不知道我理解你想要做什麼,但是當你調用「getCurrentPosition」你通過了第一個參數是將與位置被調用一次它是方法檢索。當您在您的評論說,getCurrentPosition總是立即返回,但回調方法將被調用,如果用戶位置可被檢索(它可能永遠不會被調用):

navigator.geolocation.getCurrentPosition(function(position) { 
    var lat = position.coords.latitude; 
    var lon = position.coords.longitude; 
    //do something like recent the Map 
}); 

您需要首先創建單張地圖一些默認座標,然後使用提供給回調方法的座標重新映射地圖。

相關問題