2011-05-25 33 views
1

我主要使用PHP代碼,我沒有豐富的JavaScript範圍知識;希望有人能很快解決我的問題。如評論所示,檢查mapCenter.Latitude和mapCenter.Longitude - 它們顯示爲空。firefox位置感知+ javascript範圍

如果將執行,如果位置感知在瀏覽器中可用 - 我敢肯定它適用於我,我用alert()測試它。此外,我知道它正確地抓住position.coords.latitude/longitude,因爲我用alert()的方法測試了這些...但是這些值在函數之外並不是持久的。這可能是微不足道的 - 解決方法是什麼?

function load(){ 
     map = new VEMap('MapDiv'); 
     map.LoadMap(); 
     mapCenter = new VELatLong(); 
     if(navigator.geolocation) 
     { 
      navigator.geolocation.getCurrentPosition(function(position) 
      { 
       mapCenter.Latitude = position.coords.latitude; 
       mapCenter.Longitude = position.coords.longitude; 

      });    
     }   

     //Inspecting mapCenter.Latitude & mapCenter.Longitude shows empty... 

     map.SetCenterAndZoom(mapCenter, 15); 
... 
... 
} 

謝謝!

回答

3

getCurrentPosition接受回調,告訴我它正在執行異步操作。所以發生的事情是你的匿名函數中的代碼最有可能在調用map.setCenterAndZoom(mapCenter, 15)之後執行。當您使用異步操作時,執行過程不再等待完成(因此是異步)而進入異步調用。因此,如果您依賴於來自異步調用的任何數據,則需要確保在回調中處理它,因爲否則很可能無法使用它。

你應該做的是撥打電話回調,像這樣:

function load(){ 
     map = new VEMap('MapDiv'); 
     map.LoadMap(); 
     mapCenter = new VELatLong(); 
     if(navigator.geolocation) 
     { 
      navigator.geolocation.getCurrentPosition(function(position) 
      { 
       mapCenter.Latitude = position.coords.latitude; 
       mapCenter.Longitude = position.coords.longitude; 
       map.SetCenterAndZoom(mapCenter, 15); 
       //any other code that needs to deal with mapCenter 
      });    
     }   
} 

map將可匿名函數裏面,因爲它就像一個閉合,所以它在詞法勢必範圍在其中被定義。

+0

這是完美的,謝謝你的代碼,和優秀的解釋。乾杯! – 2011-05-25 22:14:22

0

geolocation.getCurrentPosition()是asynchronous。這意味着getCurrentPosition()在傳遞給它的函數被調用之前返回。瀏覽器存儲您的功能,計算座標,然後最終調用您的功能。這會在load()函數完成後很長時間發生,因此mapCenter爲什麼是空的。

一個簡單的解決方法是把所有後續的代碼是依賴於mapCenter步入回調函數:

... 
    navigator.geolocation.getCurrentPosition(function(position) 
    { 
     mapCenter.Latitude = position.coords.latitude; 
     mapCenter.Longitude = position.coords.longitude; 
     ... 
     map.SetCenterAndZoom(mapCenter, 15); 
     ... 
    }); 
}