【问题标题】:Geolocation Google Maps Links jQuery地理位置 谷歌地图 链接 jQuery
【发布时间】:2012-05-04 14:57:30
【问题描述】:

当我点击手机上的链接时,我希望提示用户是否允许检测该位置,如果允许,则打开 Google 地图,其路线从当前位置开始到达终点。

这是我拥有的,但是当我点击链接时,它会转到备用默认链接。

<a class="geo" href="http://maps.google.com/maps?ll=40.822419,-73.993124">Get Directions</a>

$("a.geo").click(function(e)) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getLoc, handle_errors);
    }
    e.preventDefault();
});

function getLoc(position) {
    var geoLat = position.coords.latitude;
    var geoLon = position.coords.longitude;
    var gmapLink = "http://maps.google.com/maps?saddr=" + geoLat + "," + geoLon + "&daddr=40.822419,-73.993124";
    $("a.geo").attr("href", gmapLink);
}

在用户点击链接后,如何将新链接替换为用户位置的 href?

【问题讨论】:

    标签: jquery html google-maps-api-3


    【解决方案1】:

    替换更改href 属性的行:

    $("a.geo").attr("href", gmapLink);
    

    带有重定向:

    window.location.assign(gmapLink);
    

    还值得将e.preventDefault() 移动到if (navigator.geolocation) 块内,这样如果没有可用的地理位置,用户仍然可以访问谷歌地图并可以自己插入他们的位置。

    【讨论】:

    • 谢谢。一个问题 - 如果用户不希望网站获取位置,我如何将他们重定向到最初在 html 中设置的 href(带有谷歌地图链接)?
    【解决方案2】:

    以下内容对我有用。请注意,我将上下文代理到 getLoc 函数,因此 $(this) 仍然是我们在获取回调时按下的链接,并添加了一个单击触发器来实际单击该链接。另一种解决方案是使用 window.location。

    $("a.geo").click(function(e) {               
        if (navigator.geolocation) {
            e.preventDefault();
            navigator.geolocation.getCurrentPosition(
                 $.proxy( getLoc, $(this) )                    
                , handle_errors);          
        }
    });
    
    function getLoc(position) {                     
        var geoLat = position.coords.latitude;
        var geoLon = position.coords.longitude;
        var gmapLink = "http://maps.google.com/maps?saddr=" + geoLat + "," + geoLon + "&daddr=40.822419,-73.993124";        
        $(this).attr("href", gmapLink);
        $(this).trigger('click');
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2012-03-23
      相关资源
      最近更新 更多