I'm trying to use HTML5s geolocation to get the latitude and longitude of a user location and then pass those values to an ajax call.
What am I trying to do?
What have I done so far?
So far, I have placed the ajax call within the success callback so that as soon as the result is available, it makes the ajax call. I would now like to wait until incase there is an error message too so that incase of an error, an ajax call can be made with null values passed.
What is happening instead?
When the user allows a location to be shared, the ajax call is made however, if the user decides not to share a location, the ajax call isnt made and instead prints out an error messages. I'm not sure how to change my code so as to listen to both success and error callbacks before making the AJAX call.
Code I have written so far:
//error callback
var showError = function(error) {
var errorMessage = "Unknown Error";
switch(error.code) {
case error.PERMISSION_DENIED:
errorMessage = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
errorMessage = "Location information is unavailable.";
break;
case error.TIMEOUT:
errorMessage = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
errorMessage = "An unknown error occurred.";
break;
}
console.log(errorMessage);
};
var lat = function(callback) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
callback.call(null, lat, lon);
}, showError);
};
//get the latitude and longitude
var getPosition = function() {
lat(function (latitude, longitude) {
alert("lat: " + latitude + ", lon: " + longitude);
//AJAX call made here once the latitude and longitude are returned.
});
};
getPosition();
I'm not 100% sure I understood you correctly, but you can still call the callback function on error, after you print the error for yourself, like so:
var lat = function(callback) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
callback(lat, lon);
}, function(error) {
showError(error);
callback();
});
};
var getPosition = function() {
lat(function (latitude, longitude) {
alert("lat: " + latitude + ", lon: " + longitude);
// AJAX call made here once the latitude and longitude are returned.
// In case of error, latitude and longitude will both be undefined
});
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments