当我尝试从反向地理编码方法中的URL获取json时出现问题: 我根据stackoverflow上找到的解决方案尝试了这个。 当我尝试在警报中显示json时显示:undefined
adressReverseGeoCode(item: any, elementId: any) {
var getJSON = (url: any, callback: any) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = () => {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('http://nominatim.openstreetmap.org/reverse?format=json&lat=' + item.latitude + '&' + 'lon=' + item.longitude + '&addressdetails=1',
(err: any, data: any) => {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert(data.result);
}
});
}
我想从json获取“display_name”,以便稍后将其放入文本输入中。 您可以尝试此链接查看json文件
{
"place_id":"154253419",
"licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright",
"osm_type":"way",
"osm_id":"424211755",
"lat":"-23.56183",
"lon":"-46.6598392",
"display_name":"Alameda Ministro Rocha Azevedo, Jardim Paulista, São Paulo, Microrregião de São Paulo, RMSP, Mesorregião Metropolitana de São Paulo, São Paulo, Southeast Region, 01410-001, Brazil",
"address":{"road":"Alameda Ministro Rocha Azevedo","suburb":"Jardim Paulista","city_district":"Jardim Paulista","city":"São Paulo","county":"Microrregião de São Paulo","state_district":"Mesorregião Metropolitana de São Paulo","state":"São Paulo","postcode":"01410-001","country":"Brazil","country_code":"br"},
"boundingbox":["-23.5642064","-23.5601209","-46.662319","-46.6580485"]
}
提前感谢您提供给我的任何帮助!
答案 0 :(得分:1)
没有data.result!这就是为什么它是未定义的。您的数据是JSON。所以只需要data.display_name。大概!
var obj = JSON.parse(data); // as suggested by @charlietfl
console.log(obj.display_name);
alert(obj.display_name);