Torrezzzz
Torrezzzz

Reputation: 307

Load js function only once onload

I want this JS function to be called only once when the page is loaded .

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

function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + 
"<br>Longitude: " + position.coords.longitude;  
    window.location.href = "?    latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
    var flag = true;
}

Upvotes: 0

Views: 320

Answers (3)

imbearr
imbearr

Reputation: 1009

Your code it's a big closure! It generate new request on this step:

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

You can use different ways:

  1. simple parse window.location.href on load and don't ask location if (window.location.href.indexOf('?')!=-1)
  2. mark client with browser data storage or coockies, and check it before ask location.
  3. use Ajax for send location info to server:

    var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
    req.onreadystatechange=function(){if((req.readyState==4)&&(req.status==200)){ console.log('location was sended to server'); }};
    req.open("GET","?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude,true);
    req.send(null);
    

Upvotes: 0

radiovisual
radiovisual

Reputation: 6458

You can simply use the onload event handler:

<body onload="getLocation()">

This will fire as soon as the page is ready.

Alternatively, you can use jQuery's .ready()like this:

$(document).ready(function(){
    getLocation();
});

Upvotes: 0

winhowes
winhowes

Reputation: 8065

It's going into an infinite loop because you are redirecting the page with

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

every time the page loads. Instead you could do something like this for showPosition():

function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;  
    var query = "?    latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
    var stateObj = { query: query };
    history.pushState(stateObj, "query added", query);
    var flag = true;
}

This will add the query parameters to the URL without refreshing the page. For more details on history.pushState(), see https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

Upvotes: 1

Related Questions