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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9695125/
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-26 07:29:56  来源:igfitidea点击:

Easiest way to get Zip Code from City Name

javascriptasp.net

提问by Troy Loberger

I wanted to mess around with an assignment of mine and search for weather by city name rather than by zip code(how i have it set up now). What would be the easiest way to use a city name input string and get a zip code out of it? Help is much appreciated! Thanks!

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

回答by Alec Sanger

Google can help you out here!

谷歌可以在这里帮助你!

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

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

The zip is actually called "postal_code" by Google.

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

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

For example, let's say you want to get the zip for Clarkston, MI...

例如,假设您想获取密歇根州克拉克斯顿的邮编...

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

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

This returns:

这将返回:

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

EDIT

编辑

If you're not receiving a postal code with that first call, you'll have to make a second call to the same web service using the coordinates from the first call. Still very simple - the call for Stevens Point, WI would be as follows:

如果您在第一次调用时没有收到邮政编码,则必须使用第一次调用的坐标对同一 Web 服务进行第二次调用。仍然非常简单 - 威斯康星州史蒂文斯角的电话如下:

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

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

You can grab the lat/lng values from "location". Hope this helps!

您可以从“位置”获取纬度/经度值。希望这可以帮助!

回答by SergeDirect

The most popular answer above is incomplete. Please check my more up-to date answer below, where I describe my personal proven method to get the most accurate results from Google Maps API. Tested on a website with over 100 million unique locations.

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

There are many postcodes in each city.

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

I've had an issue like this one before when I had to generate over 1 million combinations of links for sitemaps with mixed locations + keywords.

我以前遇到过这样的问题,当时我不得不为混合位置 + 关键字的站点地图生成超过 100 万个链接组合。

At first, I have tried adding keywords "center", "central" & "centre" to the city name as well as the country and it worked 80% of the time, which was not good enough due to the volume I've had to accomplish.

起初,我尝试在城市名称和国家/地区添加关键字“center”、“central”和“centre”,并且在 80% 的时间里都有效,由于我拥有的数量,这还不够好去完成。

So I kept digging for a better solution and eventually, I have found 2 NEW parameters for Google Maps Geocode API, simply by copy/pasting parts of the results in the query URL.

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

Please note: This is not documented by Google and whilst it is working just now, it might not work in the future.

请注意:Google 没有记录这一点,虽然它现在可以使用,但将来可能无法使用。

1st Parameter:

第一个参数:

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

Full Example:

完整示例:

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

Also when looping through JSON sometimes POSTCODE is not in the 1st hierarchy of results, so be sure to loop through the 2nd row, if the 1st one is missing the POSTCODE.

此外,当循环 JSON 时,有时 POSTCODE 不在结果的第一个层次结构中,所以一定要循环第 2 行,如果第 1 行缺少 POSTCODE。

Here is a looping example through the array:

这是一个遍历数组的循环示例:

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;

}

Enjoy!

享受!

回答by Joe Programmer

The way I am doing it is by making two calls.

我这样做的方式是拨打两个电话。

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

The global variables are available to the rest of the script after the function call. The function returns false on failure or true on success. Appropriate error handling should be done in the main code.

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

回答by Chandrika Shah

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