Reputation: 928
I have been browsing for hours now to find a solution. I have a low knowledge of JavaScript, I am actually learning it.
I am encoutering a problem with getting the GPS position of my user. I want : - Get the position of the user (jQuery). - Transmit it to the server side via Ajax > PHP.
Here is my JS code :
$(document).ready(function () {
initCoords();
});
function initCoords() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(updateLocation, errorHandler, {enableHighAccuracy: false, maximumAge: 60000, timeout: 27000});
} else
{
alert('Wrong browser.');
}
}
function updateLocation(position)
{
var longitude=position.coords.longitude;
var latitude=position.coords.latitude;
console.log(longitude);
$.ajax({
url: "../../ajax/account/handlegeolocation",
type: "post",
dataType: "json",
data: {"longitude": longitude, "latitude": latitude},
success: function (response) {
console.log(response.message);
},
error: function (xmlhttprequest, textstatus, message) {
console.log(message);
}
}).then(function () {
setTimeout(updateLocation, 30);
});
}
function errorHandler(error)
{
console.log('Geolocation error : code ' + error.code + ' - ' + error.message);
}
What I am surprised is what I see when loading the page. The position is returned, but JS says the object that returns the position is undefined.
Thank you for your help !
Upvotes: 0
Views: 1016
Reputation: 141
This is because you are not passing position object from
setTimeout(updateLocation, 30);
calling to function initCoords
from timeout will solve your problem.
Or here is your code with some edit and without any error.
$(document).ready(function () {
initCoords();
});
function initCoords() {
if (navigator.geolocation) {
getGeoLocation();
} else {
alert('Wrong browser.');
}
}
function getGeoLocation() {
navigator.geolocation.getCurrentPosition(updateLocation, errorHandler, { enableHighAccuracy: false, maximumAge: 60000, timeout: 27000 });
}
function updateLocation(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
$.ajax({
url: "../../ajax/account/handlegeolocation",
type: "post",
dataType: "json",
data: { "longitude": longitude, "latitude": latitude },
success: function (response) {
console.log(response.message);
},
error: function (xmlhttprequest, textstatus, message) {
console.log(message);
}
}).then(function () {
setTimeout(getGeoLocation, 30);
});
}
function errorHandler(error) {
console.log('Geolocation error : code ' + error.code + ' - ' + error.message);
}
Upvotes: 1