I have the following script which reloads the page so I can grab the latitude and longitude variables. I'd like it to reload once, however, the page continues to refresh over and over again. I can't seem to figure out why. Any insight would be very helpful.
Please find my code below:
window.onload = function getLocation () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition (position) {
window.location='location.php? lat='+position.coords.latitude+'&long='+position.coords.longitude;
}
You never check whether the lat
and long
parameters are set, so you keep refreshing. To avoid this, you can check these serverside:
<?php
if(isset($_GET['lat']) && isset($_GET['long'])){
?>
<h1>I know where you are!</h1>
<?php
} else {
?>
<script>
/* Your JS script */
</script>
<?php
}
?>
It sounds like you don't want to reload the page if the params are already there. To do that, add an if clause to your showPosition function:
function showPosition(position)
{
if(locationSet()) {
window.location='location.php? lat='+position.coords.latitude+'&long='+position.coords.longitude;
}
}
function locationSet() {
// TODO write function that parses window.location.search
// for lat & long params & returns true if both set
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.