【问题标题】:Get value based on types from Google Geocoding API JSON response with jQuery使用 jQuery 根据来自 Google Geocoding API JSON 响应的类型获取值
【发布时间】:2017-05-08 09:48:12
【问题描述】:

我正在从 Google Geocoding API 获取 JSON 响应

它的格式是这样的:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Department of Information science and engineering",
               "short_name" : "Department of Information science and engineering",
               "types" : [ "premise" ]
            },
            {
               "long_name" : "Gokul",
               "short_name" : "Gokul",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Hubballi",
               "short_name" : "Hubballi",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Dharwad",
               "short_name" : "Dharwad",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Karnataka",
               "short_name" : "KA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "580030",
               "short_name" : "580030",
               "types" : [ "postal_code" ]
            }

现在我可以使用

获取 JavaScript 中的属性
"Postal Code:" + json.results[0].address_components[6].long_name

但根据我的研究,我发现address_components[6] 可能并不总是相同的数据。所以我想根据类型获取值,这样我总能得到正确的数据。

现在我找到了一种使用 php 的方法:

foreach ($jsondata["results"] as $result) {
    foreach ($result["address_components"] as $address) {
        if (in_array("sublocality", $address["types"])) {
            $city = $address["long_name"];
        }
    }
}

但我不知道如何遍历每个结果并根据 JavaScript/JQuery 中的类型获取值。

谁能告诉我它是怎么做的?

【问题讨论】:

    标签: javascript jquery json google-maps foreach


    【解决方案1】:

    您可以使用下面给出的代码(纯 JavaScript),它实现了您使用 PHP 实现的相同功能。运行代码 sn -p 以查看输出。

    var results = [{
      "address_components": [{
        "long_name": "Department of Information science and engineering",
        "short_name": "Department of Information science and engineering",
        "types": ["premise"]
      }, {
        "long_name": "Gokul",
        "short_name": "Gokul",
        "types": ["political", "sublocality", "sublocality_level_1"]
      }, {
        "long_name": "Hubballi",
        "short_name": "Hubballi",
        "types": ["locality", "political"]
      }, {
        "long_name": "Dharwad",
        "short_name": "Dharwad",
        "types": ["administrative_area_level_2", "political"]
      }, {
        "long_name": "Karnataka",
        "short_name": "KA",
        "types": ["administrative_area_level_1", "political"]
      }, {
        "long_name": "India",
        "short_name": "IN",
        "types": ["country", "political"]
      }, {
        "long_name": "580030",
        "short_name": "580030",
        "types": ["postal_code"]
      }]
    }];
    
    for (result of results) {
      for (address of result.address_components) {
        if (address.types.indexOf("sublocality") != -1) {
          var city = address.long_name;
          alert(city);
        }
      }
    }

    【讨论】:

      【解决方案2】:

      你可以使用jQuery的$.each()实现

      $.each(jsondata.results, (index, result) => { // <-- ES2016 notation
          $.each(result.address_components, (jndex, address) => {
              if (typeof address.types.sublocality != "undefined"){ // check if value is in an array
                  var city = address.long_name;
              }
          });
      });
      

      【讨论】:

        【解决方案3】:

        Javascript

        var x = {
           "results" : [
              {
                 "address_components" : [
                    {
                       "long_name" : "Department of Information science and engineering",
                       "short_name" : "Department of Information science and engineering",
                       "types" : [ "premise" ]
                    },
                    {
                       "long_name" : "Gokul",
                       "short_name" : "Gokul",
                       "types" : [ "political", "sublocality", "sublocality_level_1" ]
                    },
                    {
                       "long_name" : "Hubballi",
                       "short_name" : "Hubballi",
                       "types" : [ "locality", "political" ]
                    },
                    {
                       "long_name" : "Dharwad",
                       "short_name" : "Dharwad",
                       "types" : [ "administrative_area_level_2", "political" ]
                    },
                    {
                       "long_name" : "Karnataka",
                       "short_name" : "KA",
                       "types" : [ "administrative_area_level_1", "political" ]
                    },
                    {
                       "long_name" : "India",
                       "short_name" : "IN",
                       "types" : [ "country", "political" ]
                    },
                    {
                       "long_name" : "580030",
                       "short_name" : "580030",
                       "types" : [ "postal_code" ]
        						}
        		]
        	}
        ]
        }
        
        x.results.forEach(function(elem,index){
        			elem[Object.keys(elem)].forEach(function(el,i){
        					var city = (el.types.includes('sublocality')) ? el.long_name : 'None';
        					console.log(city)
        			});
        })

        【讨论】:

          【解决方案4】:

          我个人的习惯是编写一个带参数的函数来获取我想要的数据,即使是从静态源。所以我来了。

          function get_address(json_data, types, short_name) {
          // types - the types value that you want to fetch. 
          // Eg: "administrative_area_level_2", "country"
          // short_name - boolean indicating whether we need short name or long name
          // true - short name fetched. false - long name fetched
          
              short_name = typeof short_name == 'undefined' ? false : short_name //false by default
          
              results = [];
              for (var i=0; i<json_data.results.length; i++) {
                  var ad_comp = json_data.results[i].address_components;
                  for (var j=0; j<ad_comp.length; j++) {
                      // Check whether ad_comp exists
                      if (ad_comp[j].types.indexOf(types) !== -1) {
                          results.push(short_name ? ad_comp[j].short_name : ad_comp[j].long_name);
                      }
                  }
              }
          
              // Return single match or multiple matches.
              if (results.length == 1) {
                  return results[0];
              } else {
                  return results;
              }
          }
          
          // Call function to get data.
          var postal_code = get_address(jsondata, "postal_code");
          

          对于 jquery 版本,您可以将 for 循环替换为 $.each 和 indexOf 替换为 $.inArray。但概念是一样的。

          【讨论】:

          • 为了理解和记录,你应该确保这个函数总是以相同的格式返回它的数据。因此,如果您将其命名为getAddress,则意味着它将返回一个地址。如果您将其命名为getAddresses,它将返回一个地址数组。哦,if(results.length == 0) 然后results[0] 将是undefined。
          • 同意。编辑答案以修复错误。我更专注于功能,忽略了命名约定。
          【解决方案5】:
          correct in above get_address answer:
          function get_address(json_data, types, short_name) {
          // types - the types value that you want to fetch.
          // Eg: "administrative_area_level_2", "country"
          // short_name - boolean indicating whether we need short name or long name
          // true - short name fetched. false - long name fetched
          
              short_name = typeof short_name == 'undefined' ? false : short_name //false by default
          
              tmpResults = [];
          
              $.each(json_data, (index, result) => { // <-- ES2016 notation
                  $.each(result.address_components, (jndex, address) => {
                      if (address.types.indexOf(types) != -1){ // check if value is in an array
                          tmpResults(short_name ? address.short_name : address.long_name);
                      }
                  });
              });
          
              // Return single match or multiple matches.
              if (tmpResults.length == 1) {
                  return tmpResults[0];
              } else {
                  return tmpResults;
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-09-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多