Load js function only once onload - javascript

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;
}

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

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();
});

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:
simple parse window.location.href on load and don't ask location if
(window.location.href.indexOf('?')!=-1)
mark client with browser data storage or coockies, and check it before ask location.
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);

Related

Geolocation script not returning value

I am trying to use Javascript for finding user location but it is not giving me any value, my code is below
<script>
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
document.getElementById('startLat').innerHTML = startPos.coords.latitude;
document.getElementById('startLon').innerHTML = startPos.coords.longitude;
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
</script>
<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
The HTML5 Geolocation API allows you to get a user's Latitude/Longitude with some JavaScript (if the browser is compatible, and if the user allows access to his/her location).
You can then reverse-geocode the location to get an address, there are several free reverse-geocoding services other than Google's API.
you can also check out this link How to get geographical location of an IP address in PHP for more understanding
Example:
<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.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
If you have elements with id's "startLat" and "startLon" in your HTML, it'll work
Just add in HTML:
<p id="startLat"></p>
<p id="startLon"></p>
You can delete this line, actually:
<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
To use Latitude/Longitude in your PHP you can send the values via JS
In HTML
<script>
function sendData(value) {
var request = new XMLHttpRequest();
request.open('post', 'DESTINATION.PHP', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('data=' + value);
}
</script>
Or as a hidden form input
and access in PHP
if(isset($_POST['data'])){
$data = $_POST['data'];
// Do stuff...
}

redirection using ajax with javascript variables passed in the url.

I am doing the following to pass the javascript variable from the view to
the controller:
default/rough2.html
{{extend 'layout.html'}}
<p id="demo">
</p>
<script>
var x=document.getElementById("demo");
jQuery(document).ready(function(){
geolocation();
})
function geolocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon= position.coords.longitude;
ajax('{{=URL('default','rough3')}}'+'?lat='+lat+'&lon='+lon,[],':eval');
}
</script>
rough3() function
def rough3():
lat1=request.vars.lat
lon1=request.vars.lon
...........................
.......................
But it is "not getting redirected to rough3.html".I do not understand
why?Any help is highly appreciated!
Regards,
T
If you want to do a redirect via Javascript, just set window.location (an Ajax call does not load a new page in the browser window):
window.location = '{{=URL('default', 'rough3')}}' + '?lat=' + lat + '&lon=' + lon;
The entire point of Ajax is that it makes the HTTP request without leaving the current page.
If you want to go to a new URL, then assign it to location, don't use Ajax.

GeoLocation fetching wrong latitude longitude

I am trying to fetch the current location using the geolocation . A month before it was giving correct location but not am getting different location . I have used the same code as below.
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;
*/ var query = "?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
var stateObj = { query: query };
history.pushState(stateObj, "query added", query);
var flag = true;
/*var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange=function(){if((r.readyState==4)&&(r.status==200)){ console.log('location was sended to server'); }};
req.open("GET","?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude,true);
req.send(null);
*/
}
Another problem is its fetching the latlong based on isp not on IP. So if i use this code using mobile internet ! It gives latlong of another state. Is there any way to make this work again?

Post data using javascript

Trying to post data using javascript (when the page load)
The coordinates are generated but nothing else hapens, What am I doing wrong...
Any help will be appreciated.
<p id="demo">Cords are displayed here...</p>
<script>
var x = document.getElementById("demo"); //this display the cords only to ensure script works
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = position.coords.latitude +" "+ position.coords.longitude; //this test if the cords are generated
lg=position.coords.latitude +" "+ position.coords.longitude;
var url = "navigator.asp"; // this page is linked to a database which saves the post
var params = "id=1&lg="+lg;
xhr.open("POST", url+"?"+params, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(params);
}
</script>

get location when pages loads

I am Building a website useing HTML, CSS and Java script. I am wanting to get the location of the user when page loads. so they do not need to press a button. I was hoping some one can help.
!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<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.";}
}
function showPosition(position){
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
Simply call the getLocation()
<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.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
getLocation()
</script>
​Fiddle : https://jsfiddle.net/ES4TF/
<p id="demo"></p>
<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.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
getLocation()
</script>
This is an update to the answer above for anyone wanting to do this in react without adding another script. Here is the code in ES2015 format for use with React etc, without needing to use any of the HTML stuff above. Just import the function.
Special thanks to the first post as mine is based off it .
const showPosition = position =>{
let loc = `Latitude:${position.coords.latitude} logitude:
${position.coords.longitude}`
console.log(loc)
return loc
}
const getLocation = () => {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
}
return false
}
then Just Import the function and Use It
If you want to get the state and zip you can use the google API. Here is the code to get geolocation and the sends to google and then gives you the state, address results. You will need to activate the google geolocation API.
//Docs - https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding
const getData = async (url) => {
let res = await fetch(url)
let json = await res.json()
console.log(json);
return json
}
const showPosition = async position =>{
let loc = `Latitude:${position.coords.latitude} logitude: ${position.coords.longitude}`
let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.coords.latitude},${position.coords.longitude}&key={GOOGLE_API_key}`
console.log(loc)
let address = await getData(url)
console.log(`results`,address)
return address
}
const getLocation = async () => {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
}
return false
}

Categories