Javascript 从地理编码中的lat和lng获取国家和州名称
我是网络开发的新手。今天,我尝试使用GoogleMapAPI通过JavaScript从经度和纬度获取国家名称和州名称。我阅读了GoogleMapAPI的文档并做了一些研究,但对此我有点困惑。我试了一下,我就是这么做的:Javascript 从地理编码中的lat和lng获取国家和州名称,javascript,google-maps-api-3,Javascript,Google Maps Api 3,我是网络开发的新手。今天,我尝试使用GoogleMapAPI通过JavaScript从经度和纬度获取国家名称和州名称。我阅读了GoogleMapAPI的文档并做了一些研究,但对此我有点困惑。我试了一下,我就是这么做的: function getCountryName(latitude, longitude){ var country; const geocoder = new google.maps.Geocoder(); geocoder.geocode({locati
function getCountryName(latitude, longitude){
var country;
const geocoder = new google.maps.Geocoder();
geocoder.geocode({location: {lat: latitude, lng: longitude}}, (results, status) => {
if(status === "OK"){
if(results[0]){
country = results[0].address_components[0].types[0].country;
}
else{
country = "N/A";
}
}
});
return country;
}
然而,我不断得到“未定义”的结果。我的方法有什么问题吗?
提前谢谢大家 您似乎对这里发生的异步编程感到困惑 基本上你有
返回国函数执行结束时的code>语句,该语句将始终未定义,因为此时尚未获取结果
您发送给geocoder.geocode
的第二个参数是一个回调函数,一旦google获取结果,就会调用该函数,这显然需要一点时间
所以你的函数应该是这样的
function getCountryName(latitude, longitude, onSucess){
const geocoder = new google.maps.Geocoder();
geocoder.geocode({location: {lat: latitude, lng: longitude}}, (results, status) => {
if(status === "OK"){
if(results[0]){
onSucess(results[0].address_components[0].types[0].country);
}
else{
onSucess("N/A");
}
}
});
return country;
}
getCountryName(1.1111, 2.2222, (country) => {
alert(country);
console.log(country);
// You can do anything here like showing it to ui or using it elsewhere
}
当你要在其他地方使用这个函数时,你必须像这样使用它
function getCountryName(latitude, longitude, onSucess){
const geocoder = new google.maps.Geocoder();
geocoder.geocode({location: {lat: latitude, lng: longitude}}, (results, status) => {
if(status === "OK"){
if(results[0]){
onSucess(results[0].address_components[0].types[0].country);
}
else{
onSucess("N/A");
}
}
});
return country;
}
getCountryName(1.1111, 2.2222, (country) => {
alert(country);
console.log(country);
// You can do anything here like showing it to ui or using it elsewhere
}
如果您想了解更多关于JS中回调的信息,请阅读以下内容