Wednesday, 28 August 2013

How do I get geolocation to return to a variable in jquery?

How do I get geolocation to return to a variable in jquery?

below is some rough code I'm working on. All I'm trying to do, right now
is return the var geoOutput so I can store it and use it for later. In the
example it should alert the city and state. I works if I alert from within
the success but returns as undefined when outside the geolocation
function.
$(function(){
var geoOutput;
var geoGet;
function getGeoLocation(geoType,displayType){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(geoSuccess,
geoError);
}
else {
$('.your-location').remove();
}
function geoSuccess(position) {
console.log(position.coords.latitude+',
'+position.coords.longitude);
var geoCoder = new google.maps.Geocoder();
var userLocation = new
google.maps.LatLng(position.coords.latitude,position.coords.longitude);
geoCoder.geocode({'latLng':userLocation},
function(results,status){
if (status == google.maps.GeocoderStatus.OK) {
if (results) {
if(geoType == "zip") {
geoOutput =
results[2].address_components[0].long_name;
}
if(geoType == "state") {
geoOutput =
results[6].address_components[0].long_name;
}
if(geoType == "city") {
geoOutput =
results[3].address_components[0].long_name;
}
if(geoType == "cityState") {
geoOutput =
results[3].address_components[0].long_name+",
"+results[6].address_components[0].long_name;
}
if(geoType == "coords") {
geoOutput =
position.coords.latitude+","+position.coords.longitude;
}
if(geoType == "longitude") {
geoOutput = position.coords.longitude;
}
if(geoType == "latitude") {
geoOutput = position.coords.latitude;
}
if(displayType)
$('.your-location').text(geoOutput);
return geoOutput;
} else {
console.log('Google did not return any results.');
$('.your-location').remove();
}
} else {
console.log("Reverse Geocoding failed due to: " +
status);
$('.your-location').remove();
}
});
}
function geoError(err) {
if (err.code == 1) {
//console.log('The user denied the request for location
information.');
$('.your-location').text('State Not Found');
} else if (err.code == 2) {
//console.log('Your location information is unavailable.');
$('.your-location').remove();
} else if (err.code == 3) {
//console.log('The request to get your location timed out.');
$('.your-location').remove();
} else {
//console.log('An unknown error occurred while requesting
your location.');
$('.your-location').remove();
}
}
}
alert(getGeoLocation("cityState",false));
});

No comments:

Post a Comment