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

Posted

技术标签:

【中文标题】Jquery Geocomplete。在页面加载时显示用户当前位置【英文标题】:Jquery Geocomplete. Show users current location on page load 【发布时间】:2013-08-06 23:25:57 【问题描述】:

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

$(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】:

为此,您需要访问导航器对象的地理位置

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

【讨论】:

感谢您的回复 Ohgodwhy。我在地图代码之后添加了它,现在它会询问我的位置,这很棒。不过,我无法将此代码应用于我的地图。我需要以某种方式将它集成到我猜的“位置”行中。 location: (navigator.geolocation), 似乎不起作用,尝试将其添加到函数中也不起作用。你有什么想法?再次感谢 @Desmond 地图不需要在构建时需要传入任何location。你只需要通过提供选项来实例化地图对象,直到你调用setCenter(pos),然后地图将加载中心,或者setCenter(some_default_pos),如果他们不支持导航器 @Desmond 我会让你轻松的,here is a jsFiddle showing how to do this 非常感谢您的帮助。现在正在使用基于位置的服务加载地图。我只需要弄清楚如何让 Geocomplete 搜索使用它,我会在我这样做的时候发回这里!再次感谢您的宝贵时间!

以上是关于Jquery Geocomplete。在页面加载时显示用户当前位置的主要内容,如果未能解决你的问题,请参考以下文章

一个js api中的jquery geocomplete和markerclusterer包括

带有地理编码器的 Geocomplete 不起作用

jquery,在页面未完全加载时加载页面

jquery是怎么实现:页面加载完毕,而图片未加载完成时,触发的事件?

用jquery实现当页面加载时定时弹出警告框,怎么实现啊?

jquery是怎么实现:页面加载完毕,而图片未加载完成时,触发的事件?