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

时间:2012-03-14 02:27:39

标签: javascript asp.net

我想弄乱我的任务并按城市名称而不是邮政编码搜索天气(我现在如何设置)。使用城市名称输入字符串并从中获取邮政编码最简单的方法是什么?非常感谢帮助!谢谢!

4 个答案:

答案 0 :(得分:13)

Google可以帮助你!

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

该邮件实际上被Google称为“postal_code”。

  "long_name": "94043",
  "short_name": "94043",
  "types": postal_code

例如,假设你想要获得Clarkston,MI的拉链......

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

修改

如果您没有收到第一次电话的邮政编码,则必须使用第一次电话的坐标再次拨打同一个网络服务。还是很简单 - 对史蒂文斯角,威斯康星州的呼吁如下:

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

您可以从“位置”获取lat / lng值。希望这有帮助!

答案 1 :(得分:1)

上面最受欢迎的答案是不完整的。请查看下面的更多最新答案,我在其中描述了我个人经过验证的方法,以便从Google Maps API获得最准确的结果。在拥有超过1亿个独特位置的网站上进行测试。

每个城市都有很多邮政编码。

我之前遇到过类似的问题,因为我必须为包含混合位置+关键字的站点地图生成超过100万个链接组合。

首先,我尝试添加关键字“center”,“central”&城市名称以及国家的“中心”,它在80%的时间里工作,由于我必须完成的工作量,这还不够好。

所以我一直在寻找更好的解决方案,最后,我找到了2个Google Maps Geocode API的新参数,只需复制/粘贴查询网址中的部分结果即可。

请注意:Google未记录此信息,虽然它刚刚开始工作,但它可能在将来无效。

第一个参数:

&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.

第二个参数:

&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;

}

享受!

答案 2 :(得分: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。应该在主代码中进行适当的错误处理。

答案 3 :(得分:-1)

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