2013-08-06 75 views
0

我正在使用針對移動網站的jquery.geocomplete.js - 我希望它加載顯示用戶在地圖上的當前位置。唯一的默認位置選項似乎是一組固定的座標或國家名稱。是否有可能展示如何在Geolocation代碼中實現這一點?這是我目前的:Jquery Geocomplete。在網頁加載時向用戶顯示當前位置

$(function(){ 
     var options = { 
      map: ".map_canvas",    
      location: [-35.3075, 149.124417], 
      mapOptions: { 
      zoom: 3 
      }, 
      zoom: 1, 
      types: ['establishment'],    
      country: 'au'    
     }; 

     $("#geocomplete").geocomplete(options).val(); 

    }); 

感謝您的任何幫助。

回答

2

你需要爲這個什麼,是訪問navigator對象

if(navigator.geolocation){ 
    /* 
    * getCurrentPosition() takes a function as a callback argument 
    * The callback takes the position object returned as an argument 
    */ 
    navigator.geolocation.getCurrentPosition(function(position){ 
     /** 
     * pos will contain the latlng object 
     * This must be passed into the setCenter instead of two float values 
     */ 
     var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); // 
     map.setCenter(pos); //center the map based on users location 
    }, function(){ 
     //client supports navigator object, but does not share their geolocation 
    }); 
}else{ 
    //client doesn't support the navigator object 
} 

當然,上面的代碼中必須出現在實例化地圖實例之後的地理位置。

您可以read the documentation about Geolocation for Google Maps API here

您還可以see the fullscreen example here

最後。 here's a jsFiddle implementing this

+0

感謝您的回覆Ohgodwhy。我在地圖代碼之後添加了它,現在要求提供我的位置,這很好。雖然我將這段代碼應用到我的地圖時遇到了麻煩。我需要以某種方式將它整合到我認爲的「位置」線。 ** location:(navigator.geolocation),**似乎不起作用,也沒有嘗試將其添加到函數中。你有什麼想法? 再次感謝 – Desmond

+0

@Desmond當你構建它時,Map *不需要傳入任何'location'。您只需通過提供選項來實例化地圖對象,直到您調用'setCenter(pos)',那麼地圖將加載中心,或者在它們不支持導航器的情況下'setCenter(some_default_pos)' – Ohgodwhy

+0

@Desmond我會讓你輕鬆,[這裏是一個jsFiddle展示如何做到這一點](http://jsfiddle.net/dLrvq/) – Ohgodwhy

相關問題