Reputation: 31
I have a script that allows the user to view locations of comms cabinets. I am trying to get html5 to pass latitude and longitude to a php script(geo.php) to update the record in the database with the map coordinates, but keep getting errors:
ReferenceError: Can't find variable: pos
this is my code. Please help me get the latitude and longitude to appear in the link to be called by ajax:
function getLocation() {
navigator.geolocation.getCurrentPosition(function(pos)
{
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
});
}
function saveLocation(building, commNo) {
getLocation();
var latitude = lat;
var longitude = lng;
alert(latitude + longitude);
document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
getMap(exchangeName, PCP);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
Upvotes: 0
Views: 76
Reputation: 318202
The geolocation API is asynchronous, just like your ajax call, so you have to wait for the results to return, and even if you did have to wait for the async call, variables are only available inside the scope where they are defined.
function getLocation(callback) {
navigator.geolocation.getCurrentPosition(function (pos) {
callback(pos.coords.latitude, pos.coords.longitude);
});
}
function saveLocation(building, commNo) {
getLocation(function(latitude, longitude) {
document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
getMap(exchangeName, PCP);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
});
}
Upvotes: 1