2010-10-04 76 views
0

我試圖做一些事情,應該是很簡單 - 但它做我的頭 我似乎無法得到一個變量從一個函數返回使用Javascript - 返回變量失敗

var where; 
if (navigator.geolocation) { 
    where = navigator.geolocation.getCurrentPosition(function (position) { 
    // okay we have a placement - BUT only show it if the accuracy is lower than 500 mtrs 
    //if (position.coords.accuracy <= 500) { 
     // put their lat lng into google 
     var meLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
     var image = "images/map_blue.png"; 
     var myMarker = new google.maps.Marker({ 
      position: meLatLng, 
      map: map, 
      title: "Your location, as provided by your browser", 
      icon: image, 
      zIndex: 50 
     }); 
    //} // end 500 mtrs test 
      return meLatLng;   
    }); 
    alert("A: "+where); 
} 

我有一個名爲全局變量在哪裏,我想用navigator.geolocation從瀏覽器接收經緯度信息,以填補它 - 它繪製在地圖上的用戶 - 但警報(在哪裏)總是返回undefined

什麼我做錯了嗎?

回答

3

簡短的回答,沒有,

時間長一點的回答,嗯......你看,問題是,它會顯示你的匿名函數返回其值的getCurrentPosition功能,這似乎犯規在返回任何東西所有。

爲了使用返回的值,你應該使用回調或處理數據的地方是......

簡單地嘗試customCallBack(meLatLng)更換return meLatLng,然後定義customCallBack某處沿線。

或者,因爲你已經在全球範圍內定義where你可以嘗試用where = meLatLng取代return meLatLng,然後從where = navigatior.geoloc....

刪除where =如果我的懷疑是正確的,最後一種方法不會工作,因爲我相信getCurrentPosition是異步的,這意味着您在調用應用程序後立即離開應用程序的標準流程。這就是爲什麼你首先提供一個函數。

+0

是的,它似乎它用完主流,所以我不得不看看這個CallBack的想法..謝謝:) – keranm 2010-10-04 18:40:01