Geolocation Google Maps Links jQuery

本秂侑毒 提交于 2019-12-24 12:25:09

问题


When I click on a link on the mobile phone, I would like a prompt to ask the user if they would like to allow the location to be detected, and if yes, open Google Maps with the directions starting from their current location to the end destination.

This is what I have, but when I click on the link, it goes to the fallback default link.

<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);
}

How do I replace the href with the new link with the user's location AFTER the user clicks on the link?


回答1:


Replace your line which changes the href attribute:

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

with a redirect:

window.location.assign(gmapLink);

It would also be worth moving the e.preventDefault() inside the if (navigator.geolocation) block, so that if there is no geolocation available, the user still goes to google maps and can insert their location themselves.




回答2:


The following works for me. Notice that I proxy the context to the getLoc function, so that $(this) is still the link we pressed when getting the callback, and added a click-trigger to actually click the link. An alternate solution is to use 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');
}


来源:https://stackoverflow.com/questions/10451282/geolocation-google-maps-links-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!