javascript 从谷歌地图解析 json 反向地理编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22185725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:39:06  来源:igfitidea点击:

Parse json from google maps reverse geocode?

javascriptjsonparsinggoogle-maps-api-3geocode

提问by Rudiger Kidd

How can I parse through the response from a reverse geocode using Google Maps JavaScript API v3.

如何使用 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);
                    }
                } 

This displays the formatted address fine in the popup, but I'm trying to take other bits out of the response, ideally the street name or route (if no street name found). But when using obj = JSON.parse(json);I keep getting this error in the console.

这会在弹出窗口中很好地显示格式化的地址,但我试图从响应中删除其他位,理想情况下是街道名称或路线(如果没有找到街道名称)。但是在使用时, obj = JSON.parse(json);我不断在控制台中收到此错误。

SyntaxError: JSON.parse: unexpected character

语法错误:JSON.parse:意外字符

if it were PHP I would do a bunch of for eachloops. Is it possible to do something similar in JavaScript ?

如果是 PHP 我会做一堆for each循环。是否可以在 JavaScript 中做类似的事情?

heres a sample

这是一个样本

{
   "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"
}

also heres a link to my dev pagewith my current code in full

还有一个指向我的开发页面链接,其中包含我当前的完整代码

In summary, how do I get "Stubbington Avenue" from that mess up there ?

总之,我如何从那里的混乱中获得“Stubbington Avenue”?

回答by nebulae

you don't need to JSON.parse those results, it's already json.

你不需要 JSON.parse 这些结果,它已经是 json。

to get "stubbington avenue" out of that valid json, you would use results[0].address_components[1].short_name

要从有效的 json 中获取“stubbington avenue”,您可以使用 results[0].address_components[1].short_name

if you wanted to build the actual address out of those address components, you can loop through and see the values printed out to the console like this:

如果您想从这些地址组件中构建实际地址,您可以循环遍历并查看打印到控制台的值,如下所示:

for(var i in results[0].address_components){
    console.log(results[0].address_components[i].short_name);
}

instead of logging them out, append them to a string, or append them to an element, whatever you wish to do with them.

与其将它们注销,不如将它们附加到一个字符串,或将它们附加到一个元素,无论您想对它们做什么。

回答by Manu

I am using Meteor and for Meteor.js it worked a bit differently in my case

我正在使用 Meteor 和 Meteor.js 在我的情况下它的工作方式有点不同

Below is the Meteor Client Side and Server Side Code that worked for me:

以下是对我有用的 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;
      }