Reputation: 39
I want to access variables lat and var lng as shown in the code below please suggest me the correct ways to access these variables in the .load
$(document).ready(function(){
function getLocation() {
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 lng= position.coords.longitude;
}
$(".content").load("page1.php?latitude="+lat+"&longitude="+lng);
});
I want to call var lat and var lng as shown in the code below please suggest me the currect ways to call this variables in the .load
Upvotes: 0
Views: 229
Reputation: 339836
The getCurrentPosition
function is asynchronous - the callback is invoked sometime later and execution continues with the rest of the function.
As such, the call to .load
should be made within the showPosition
function itself.
Don't forget that you must also call getLocation()
to start the whole process off.
For convenience, here's an untested plugin wrapper that I've just knocked up that converts the getCurrentLocation
call to a Promise interface:
(function($) {
$.geolocate = function(options) {
var def = $.Deferred();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(def.resolve, def.reject, options);
} else {
def.reject("location not available");
}
return def.promise();
};
})(jQuery);
usage:
$.geolocate().done(function(pos) {
// use pos here
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
...
}).fail(function(err) {
// 'err' is a PositionError object (if supported but not permitted)
// or a string if geolocation isn't even supported.
});
See http://jsfiddle.net/alnitak/SD79R/
Upvotes: 2
Reputation: 5483
You could move them up to .ready()
's scope:
$(document).ready(function(){
var lat;
var lng;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
lat= position.coords.latitude;
lng= position.coords.longitude;
}
$(".content").load("page1.php?latitude="+lat+"&longitude="+lng);
});
Upvotes: -1