【发布时间】:2018-04-13 14:46:37
【问题描述】:
我目前有以下代码来处理获取请求并返回地址。
address = "https://maps.googleapis.com/maps/api/geocode/json?latlng=38.8976763,-77.0387238&key=[APIKEY]"
results = httpGet(address)
console.log(results)
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
当代码执行时,它会以 JSON 格式返回以下内容。如何从以下文本中获取“formatted_address”字段?
{
"results" : [
{
"address_components" : [
{
"long_name" : "1650",
"short_name" : "1650",
"types" : [ "street_number" ]
},
{
"long_name" : "Pennsylvania Avenue Northwest",
"short_name" : "Pennsylvania Ave NW",
"types" : [ "route" ]
},
{
"long_name" : "Northwest Washington",
"short_name" : "Northwest Washington",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Washington",
"short_name" : "Washington",
"types" : [ "locality", "political" ]
},
{
"long_name" : "District of Columbia",
"short_name" : "DC",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "20504",
"short_name" : "20504",
"types" : [ "postal_code" ]
}
]
"formatted_address" : "1650 Pennsylvania Ave NW, Washington, DC 20504, USA",
"geometry" : {
"location" : {
"lat" : 38.8980085,
"lng" : -77.0389457
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 38.8993574802915,
"lng" : -77.0375967197085
},
"southwest" : {
"lat" : 38.8966595197085,
"lng" : -77.04029468029151
}
}
},
"place_id" : "ChIJY7LRgby3t4kRz3_VtbtJpfE",
"types" : [ "street_address" ]
},
}
我尝试以通常处理 JSON 文件的方式处理文件,但我仍然不熟悉正确的处理过程。会使用类似于
的东西JSON.parse(result)
当我尝试对输出进行排序时有帮助吗?任何帮助,将不胜感激。
同样,我将如何修改我的代码以使用以下 sn-p?被告知不鼓励同步请求,我应该改为创建异步请求,但我不知道如何集成它。
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
【问题讨论】:
标签: javascript json parsing google-geocoder