Jquery Geocomplete。在页面加载时向用户显示当前位置

时间:2013-08-06 23:25:57

标签: jquery google-maps mobile geolocation

我正在为移动网站使用 jquery.geocomplete.js - 我希望它加载显示用户在地图上的当前位置。唯一的默认位置选项似乎是一组固定坐标或国家/地区名称。是否可以在Geolocation代码中展示如何实现它?这就是我目前所拥有的:

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

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

    });

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您需要的是来访问导航器对象的地理位置

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