2012-07-20 111 views
0

我試圖在允許用戶縮放到他的位置的地圖上設置按鈕。我正在使用Leaflet映射庫(leaflet.cloudmade.com)。檢查使用Leaflet的locate()時用戶是否共享位置()

locate()方法效果很好,但我想確保用戶實際上共享他的位置,因爲如果瀏覽器返回一個位置,我想讓按鈕更改。下面是我一直在嘗試使用代碼:

function locateUser() { 
    try { 
     this.map.locate({setView: true}); 
    } catch(err) { 
     alert("Couldn't find your location."); 
     return false; 
    } 
    return true; 
} 

$("document").ready(function() { 
    var map = null; 
    initmap(); // This is the function that displays the map. 

    // Here is where I need to check whether the user was located. 
    // If he is located I want to switch the button to one that will 
    // reset the view. 
    var is_located = 0; 
    $("#myLocation").click(function() { 
     if (is_located == 0) { 
      if (locateUser()){ 
       is_located = 1; 
       $(this).attr('value', 'WILMINGTON'); 
      }; 
     } else if (is_located == 1) { 
      $(this).attr('value', 'MY LOCATION'); 
      is_located = 0; 
     }; 
    }); 
}); 

傳單文檔說的定位()方法將返回locationfound事件或locationerror事件,但是當我嘗試登錄什麼定位()返回時,我只是得到一個對象,它並不清楚它是否找到了用戶的位置。

回答

1

Leaflet的locate()方法將只返回Map對象而不是地理定位調用的狀態。傳單將然而試圖地理位置後兩個事件的火一個:

  • locationfound
  • locationerror

我已經上傳使用這些事件的一個例子:http://jsfiddle.net/XwbsU/5/

你可以看到我已經註冊到這些事件中的每一個以確定地理定位呼叫是否成功。

希望有所幫助。

+0

完美。我轉移了一些東西,把'$(this).attr('value','WILMINGTON');'放到'... on('locationfound'...')的回調函數中,當我清理它時,會發布結束代碼。非常感謝您的幫助。 – patsweet 2012-07-26 16:57:55

相關問題