下面是我正在研究的一些粗略代码。我现在要做的就是返回var geoOutput,这样我就可以存储它并在以后使用它。在示例中,它应警告城市和州。如果我在成功范围内发出警报,但在地理定位功能之外返回为未定义,我会工作。
$(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));
});
答案 0 :(得分:0)
您也应该返回成功函数。有关从嵌套函数返回的更多详细信息,请参阅此答案:Return value from nested function in Javascript