从城市名称获取邮政编码的最简单方法

4

我想尝试一下我的作业,并通过城市名称而不是邮政编码(目前的设置)搜索天气。使用城市名称输入字符串并获取邮政编码的最简单方法是什么?非常感谢您的帮助!谢谢!


有一个jQuery插件可以实现这个功能 https://github.com/Loceo/loceo-jquery-plugin - Gustav
你觉得城市和邮政编码之间存在一对一的映射关系吗?大城市可能包含数十个邮政编码,而且城市不同地区的天气通常也会有很大差异。 - Jim Garrison
4个回答

15

谷歌可以在这里帮到你!

https://developers.google.com/maps/documentation/geocoding/

由Google称为“邮政编码”,而不是“zip”。

  "long_name": "94043",
  "short_name": "94043",
  "types": postal_code
例如,假设您想获取密歇根州克拉克斯顿的邮政编码...

http://maps.googleapis.com/maps/api/geocode/json?address=Clarkston+MI&sensor=true

这将返回:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Clarkston",
               "short_name" : "Clarkston",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Oakland",
               "short_name" : "Oakland",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Michigan",
               "short_name" : "MI",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "48346",
               "short_name" : "48346",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Clarkston, MI 48346, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 42.7418310,
                  "lng" : -83.41402409999999
               },
               "southwest" : {
                  "lat" : 42.7252370,
                  "lng" : -83.42880730000002
               }
            },
            "location" : {
               "lat" : 42.73511960,
               "lng" : -83.41929410
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 42.74331460,
                  "lng" : -83.40328670
               },
               "southwest" : {
                  "lat" : 42.72692350,
                  "lng" : -83.43530149999999
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

编辑

如果您在第一个调用中没有收到邮政编码,则需要使用第一个调用返回的坐标再次调用同一网络服务。仍然非常简单 - 对于WI州史蒂文斯点市的呼叫如下:

http://maps.googleapis.com/maps/api/geocode/json?latlng=44.52357920000001,-89.5745630&sensor=true

您可以从"location"中获取纬度/经度值。希望能帮到您!


1
好的,我认为这很棒,已经实现了,但我的周边地区没有任何邮政编码返回:Green Bay wi,Stevens Point wi,wausau wi ... - Troy Loberger
1
有趣。那么我想你就需要再多走一步了。如果第一次运行时没有提供邮政编码,请从“位置”中获取纬度和经度值,并通过相同的网络服务运行它。请看我的更新。 - Alec Sanger
这个答案不完整。请查看我的更新答案,其中我描述了我个人的经过验证的方法,以从Google Maps API获得最准确的结果。在一个拥有超过1亿个独特位置的网站上进行了测试。 https://dev59.com/1WHVa4cB1Zd3GeqPnYHM#49517473 - SergeDirect

2
上面最受欢迎的答案是不完整的。请查看下面更为更新的答案,我在其中描述了我个人验证过的从Google Maps API获得最准确结果的方法。在一个拥有超过1亿个独特位置的网站上进行了测试。
每个城市都有许多邮政编码。
在我以前遇到类似问题时,我必须生成100万个链接组合,包含混合位置和关键词。首先,我尝试将"center"、"central"和"centre"这些关键词添加到城市名称以及国家中,它可以80%地工作,但由于我需要完成的数量太大,这并不好。
所以我继续寻找更好的解决方案,最终我发现了Google Maps Geocode API的2个新参数,只需按照查询URL中的部分内容进行复制/粘贴即可。
请注意:这不是Google文档记录的,并且虽然它目前正在工作,但未来可能无法使用。 第1个参数:
&components=country:UK // where "UK" is a country of choice, by utilising this method, rather than adding the Country to the City name, you will avoid clashes and reduce the risk of not getting the postcode.

2nd Parameter:

&location_type=GEOMETRIC_CENTER& // as is, this will get you a place closest to the central geometrical location of the town/city. 

完整示例:

var city_name = 'Edinburgh'; // City/Town/Place Name
var country_code = 'GB'; // Great Britain 
var key = 'AIzaSyBk********************cM' // Google API Key

var query = https://maps.googleapis.com/maps/api/geocode/json?address='+city_name+'&components=country:'+country_code+'&location_type=GEOMETRIC_CENTER&key='+key+'&sensor=false

当遍历JSON时,有时POSTCODE不在结果的第一层级中,因此请确保在第一行缺少POSTCODE时遍历第二行。

以下是遍历数组的示例:

url = geocode_query;

fetch(url)
.then(res => res.json())
.then((out) => {
   result = JSON.parse(out);
   postcode = get_postcode(result); // HERE is Your Postcode do what you need with it
})
.catch(err => { throw err });

function get_postcode(results){ 

    city_data = results['results'][0]['address_components'];
    for(i=0;i<city_data.length;i++){
        var cv = city_data[i];
        if(typeof cv['types'][0] != 'undefined')){
            if(cv['types'][0] === 'postal_code'){
                city['postcode'] = cv['long_name'];
            }else if(cv['types'][0] === 'postal_town'){
                city['place_name'] = cv['postal_town'];
            }
        }
    }

    if(typeof city == 'undefined'){
        city_data = results['results'][1]['address_components'];
        for(i=0;i<city_data.length;i++){
            var cv = city_data[i];
            if(typeof cv['types'][0] != 'undefined')){
                if(cv['types'][0] === 'postal_code'){
                    city['postcode'] = cv['long_name'];
                }
            }
        }
    }

    return city;

}

祝您愉快!


0
我所做的方法是进行两次调用。
    On the first call my query is: geocode('address=' .$cty. ',' .$st, $key);
    $cty = city name - $st = state abbreviation - $key is my api key
    -
    On the second call my query is: geocode('latlng=' .$lat. "," .$lng, $key);
    $lat = latitude from first call - $lng = longitude from first call

---------
My function appears below.
--------------------------------------   
    function geocode($query, $key){
        global $lat, $lng, $zipcode, $city, $state;
        $url = 'https://maps.googleapis.com/maps/api/geocode/json?'.$query.'&key='.$key;
        $json_string = curlfun($url); // this uses CURL to access the url (false on fail)
        if($json_string){
            $parsed_json = json_decode($json_string, true);
        //  
            if ($parsed_json['status'] == "OK"){
                $lat = $parsed_json['results'] [0] ['geometry'] ['location'] ['lat'];
                $lng = $parsed_json['results'] [0] ['geometry'] ['location'] ['lng'];
                foreach($parsed_json['results'] [0] ['address_components'] as $a){
                    if($a ['types'] [0] == 'postal_code') $zipcode = $a ['long_name'];
                    if($a ['types'] [0] == 'locality') $city = $a ['long_name'];
                    if($a ['types'] [0] == 'administrative_area_level_1') $state = $a ['short_name'];   
                    }
                }
            else return false;
            }
        else return false;
        if(!$city) return false; // if there is no city just return false.
    return true;
        }
    ---------------------------------------------------

全局变量在函数调用后对脚本的其余部分可用。函数在失败时返回false,在成功时返回true。应在主代码中进行适当的错误处理。


curlfun是什么?我没有看到该函数的声明。 - MaxRocket
这段代码只是一个更大程序的片段,展示了查询API的功能。curlfun()是一个函数,它使用PHP cURL从提供的URL返回数据。 - Joe Programmer

-2
var res; // store response in res variable
var add_array  = res[0].address_components; //add_array = {
               "long_name" : "Clarkston",
               "short_name" : "Clarkston",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Oakland",
               "short_name" : "Oakland",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Michigan",
               "short_name" : "MI",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "48346",
               "short_name" : "48346",
               "types" : [ "postal_code" ]
            }
    var add_array = add_array[add_array.length-1]; //add_array = {
                   "long_name" : "48346",
                   "short_name" : "48346",
                   "types" : [ "postal_code" ]
                }
    var zip = add_array.long_name;  //zip = 48346

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接