Darren
Darren

Reputation: 11

javascript geolocation not working unless I include alerts to display/delay the script

I am having a problem with the GeoLocation API. Bascially I am trying to link to Google Maps (not embed) based on the user's location. If geolocation cannot be used, it will default to just showing the destination. The problem I am having is that unless I put alerts in the code, it will always default to the destination only.

Here is my code:

  function findPosition(position)
  {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    mapURL = "https://maps.google.co.uk/maps?saddr=" + latitude + "," + longitude + "&daddr=50.795251,-1.107136&sensor=TRUE";

    alert("1 " +  mapURL); // Alert shows the URL correctly
  }

  if(navigator.geolocation)
  {
    navigator.geolocation.getCurrentPosition(findPosition);
  }

  alert("2 " +  mapURL); // Shows empty string as if findPosition() has not been called???
  alert("3 " +  mapURL); // Shows mapURL correctly

  if (mapURL == "")
  {
    // Set the default URL with only the destination
    mapURL = "https://maps.google.co.uk/maps?q=50.795251,-1.107136";
  }

  var link = "<a href=\"" + mapURL + "\" style=\"text-decoration:none;color:#000;\" target=\"_blank\">";

  document.write(link);
//-->
</script>

The comments next to the alerts are to demonstrate how the code works with them, however if the alerts are removed it always sets the destination only default URL.

I don't understand why alert 1 is showing the correct URL yet 2 is showing nothing, despite the fact that it should be processed after alert 1?

Any help would be appreciated.

Upvotes: 0

Views: 690

Answers (1)

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31580

This happens because navigator.geolocation.getCurrentPosition is async, so one solution is to pass to it a callback, as you did, which will be called when the location has been found (or when it threw an error).

You were seeing correct results using the alerts because you were giving time to the script to recognize the location.

One solution could be to move your code in the navigator.geolocation.getCurrentPosition callback, which you called findPosition, like this:

function findPosition(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;

  mapURL = "https://maps.google.co.uk/maps?saddr=" + latitude + "," + longitude + "&daddr=50.795251,-1.107136&sensor=TRUE";
  if (mapURL == "") {
    // Set the default URL with only the destination
    mapURL = "https://maps.google.co.uk/maps?q=50.795251,-1.107136";
  }

  var link = "<a href=\"" + mapURL + "\" style=\"text-decoration:none;color:#000;\" target=\"_blank\">";
  document.write(link);
}  

if(navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(findPosition);
}

Upvotes: 1

Related Questions