0

I tried to take the geolocation coordinates and send them to the url when the page is loaded.

I used the onload function in javascript. When I run the js it works but it refreshes itself repeatedly.

<script>

var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
window.onload = getLocation;

function showPosition(position) {
 window.location.href = "test_loc.php?latitude=" + position.coords.latitude +
  "&longitude=" + position.coords.longitude;

}
</script>
bcperth
  • 2,191
  • 1
  • 10
  • 16

3 Answers3

1

The reload is triggered by the following line, which appends the latitude and longitude becoz of an async call:

window.location.href = "test_loc.php?latitude=" + position.coords.latitude + "&longitude=" + position.coords.longitude;

What you may do is, you might check if the parameters exist and you can stop the callback. Please see this: How to get the value from the GET parameters?

With the answer from the other question, you may implement something like:

function showPosition(position) {
  if (typeof parse_query_string("latitude") == "undefined")
    window.location.href = "test_loc.php?latitude=" + position.coords.latitude + "&longitude=" + position.coords.longitude;
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

Because you pass showPosition as a success callback to geolocation.getCurrentPosition which then sets the location.href which reloads the page.

Code Spirit
  • 3,992
  • 4
  • 23
  • 34
0

Every time you load the page, you call getLocation() via the "onload" event, which in turn calls getCurrentPosition(), which in turn reloads the page with window.location.href. Then, when the page reloads, the onload event fires again and the whole thing starts once more from the beginning.

You've basically created an infinite loop.

Is it really necessary to refresh the page just to pass the co-ordinates? If you need to send them to the server, consider using AJAX instead.

ADyson
  • 57,178
  • 14
  • 51
  • 63