Forum Moderators: open

Message Too Old, No Replies

Geolocation: a strange script behaviour

         

tfetfe

10:54 am on May 18, 2018 (gmt 0)

5+ Year Member



The script below detects user location and redirects user to the page where appears Google's map with markers. When user access this page, container "status" shows text "detecting location". When location is detected, the text changes to "Location detected". It works fine in my desktop with Windows7, it works fine in my laptop with Windows 10 but:

1) My second desktop with Windows10 detects location incorrectly (~40 km from real location)

2) Mobile phones detect location correctly but only the first time. I am being asked for permission to share location. I agree and everything is OK. But when I access the same page again, I am not being asked for permission and nothing happends at all. Appears text "Detecting location" and that's all. No text change, no redirect. I have to delete browser cache and then everything works correctly (the first time).

All devices have the same IP address.

So, my questions are:

1) Why one of the devices detects location incorrectly? How to fix it?

2) How can I force mobile browsers to detect location every time when I visit the page, not only the first time?

<script>

function success(position) {
var s = document.querySelector('#status');

var lat = position.coords.latitude;
var longi = position.coords.longitude;


$.ajax({
cache: false,
method: "POST",
url: "/save.php",
data: {lat:lat,longi:longi},
success: function(d){
$('#status').html('Location detected');
}
});

window.location.href = "/showmap.php;
}

function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
}




if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}

</script>

<div id="status">Detecting your location</div>

Travis

11:15 am on May 18, 2018 (gmt 0)

5+ Year Member Top Contributors Of The Month



I have no idea how the geo localization API works. But since it's client side, may be Windows is configured differently on your both desktops.

As for your second question , put "<div id="status">Detecting your location</div>" BEFORE your <script>.

I suspect that the second call being cached, the result is returned immediately, and before the '<div>' object exists within the DOM, so when you try to access it to change the text,it might not work, and it might block the script from continuing.

tfetfe

4:24 pm on May 18, 2018 (gmt 0)

5+ Year Member



Travis, yes, <div id="status"> is before the script. I just here copied it incorrect.
That's something mysterious. From time to time the browser returns correct location but maybe from 15 pge loads 2 times the location is correct.