如何使用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);
}
}
这会在弹出窗口中显示格式化的地址,但我正在尝试从响应中取出其他位,最好是街道名称或路径(如果找不到街道名称)。但是当使用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"
}
还有link to my dev page,其中包含我当前的完整代码
总之,我如何从那里弄乱“Stubbington Avenue”?
答案 0 :(得分:9)
你不需要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);
}
而不是将它们记录下来,将它们附加到一个字符串中,或者将它们附加到一个元素上,无论你想用它们做什么。
答案 1 :(得分:0)
我正在使用Meteor和Meteor.js我的情况有点不同
以下是适用于我的Meteor客户端和服务器端代码:
// Client Side
var zipcode = $('[name=zipcode]').val();
Meteor.call('getLocationbyZipGoogleAPI', zipcode, function(error, result){
if(error){
console.log('error',error.reason);
} else {
var apidata = JSON.parse(result.content);
var longname = apidata.results[0].address_components[3].long_name;
var longaddress = apidata.results[0].formatted_address;
var finaladdress = longaddress+', '+longname;
}
});
// Server Method to Call API
'getLocationbyZipGoogleAPI': function(zip_code){
// do checks
var apiurl = 'http://maps.googleapis.com/maps/api/geocode/json?address='+zip_code+'&sensor=true';
var result = HTTP.get( apiurl );
return result;
}