Rud*_*idd 4 javascript parsing json google-maps-api-3 geocode
如何使用Google Maps JavaScript API v3解析反向地理编码的响应.
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
Run Code Online (Sandbox Code Playgroud)
这会在弹出窗口中显示格式化的地址,但我正在尝试从响应中取出其他位,最好是街道名称或路径(如果找不到街道名称).但是在使用时 obj = JSON.parse(json);我一直在控制台中收到此错误.
SyntaxError:JSON.parse:意外字符
如果它是PHP我会做一堆for each循环.是否可以在JavaScript中执行类似的操作?
这是一个样本
{
"results" : [
{
"address_components" : [
{
"long_name" : "131",
"short_name" : "131",
"types" : [ "street_number" ]
},
{
"long_name" : "Stubbington Avenue",
"short_name" : "Stubbington Ave",
"types" : [ "route" ]
},
{
"long_name" : "Portsmouth",
"short_name" : "Portsmouth",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Portsmouth",
"short_name" : "Portsmouth",
"types" : [ "administrative_area_level_3", "political" ]
},
{
"long_name" : "Portsmouth",
"short_name" : "Portsmouth",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "England",
"short_name" : "England",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United Kingdom",
"short_name" : "GB",
"types" : [ "country", "political" ]
},
{
"long_name" : "PO2",
"short_name" : "PO2",
"types" : [ "postal_code_prefix", "postal_code" ]
},
{
"long_name" : "Portsmouth",
"short_name" : "Portsmouth",
"types" : [ "postal_town" ]
}
],
"formatted_address" : "131 Stubbington Avenue, Portsmouth PO2, UK",
"geometry" : {
"location" : {
"lat" : 50.8170795,
"lng" : -1.0709701
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 50.81842848029149,
"lng" : -1.069621119708498
},
"southwest" : {
"lat" : 50.8157305197085,
"lng" : -1.072319080291502
}
}
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
Run Code Online (Sandbox Code Playgroud)
总之,如何从那里弄乱"Stubbington Avenue"?
neb*_*lae 10
你不需要JSON.parse那些结果,它已经是json了.
要从那个有效的json中获取"stubbington avenue",你会使用 results[0].address_components[1].short_name
如果你想从这些地址组件中构建实际地址,你可以循环查看打印到控制台的值,如下所示:
for(var i in results[0].address_components){
console.log(results[0].address_components[i].short_name);
}
Run Code Online (Sandbox Code Playgroud)
而不是记录它们,将它们附加到一个字符串,或将它们附加到一个元素,无论你想用它们做什么.
| 归档时间: |
|
| 查看次数: |
13079 次 |
| 最近记录: |