Reputation: 10671
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?
Upvotes: 1
Views: 1496
Reputation: 2404
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');
}
Upvotes: 0
Reputation: 337550
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.
Upvotes: 2