javascript 如何通过邮政编码确定美国县?

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

How can I determine US County by zip-code?

javascriptdatabasezipcode

提问by Karen Fisher

Is it possible to implement a function on clientside in javascript to use it like this:

是否可以在 javascript 中在客户端实现一个函数来像这样使用它:

var county = get_county(zip_code);

I mean is it possible to do it online by script? Or I have to dig some database? Or I have to buy it?

我的意思是可以通过脚本在线完成吗?或者我必须挖掘一些数据库?还是我必须要买?

Any help is appreciated!

任何帮助表示赞赏!

P.S.
By the help of Dyrandz Famador, I did this funciton for GAS:

PS
在 Dyrandz Famador 的帮助下,我为 GAS 做了这个功能:

function get_county(zip) {
 var county, response, result, adresses, i, j, n, type;
 response = Maps.newGeocoder().geocode(zip);
 for (i = 0; i < response.results.length; i++) {
   result = response.results[i];
   adresses = result.address_components;
   n = adresses.length;
   for (j=0;j<n;j++) {
     type = adresses[j].types[0];
     if (type == 'locality') county = (adresses[j].long_name);
     if (type == 'administrative_area_level_2')   {county =(adresses[j].long_name);}
   }
 }
 return (county);
}

采纳答案by Dyrandz Famador

you can use the Google Maps API to Get Locations from Zip Codes

您可以使用 Google Maps API 从邮政编码中获取位置

Google offers many API's, among them is the Maps API. In this example we'll show all the code necessary to hit Google with a zip code to get the location in the form of City, State and Country.

Google 提供了许多 API,其中包括 Maps API。在此示例中,我们将展示使用邮政编码访问 Google 以获取城市、州和国家/地区形式的位置所需的所有代码。

First thing to do is to reference Google's Map API:

首先要做的是参考 Google 的 Map API:

<script language="javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>

Next is a little form used to enter your zip code:

接下来是用于输入邮政编码的小表格:

<form>
zip: <input type="text" name="zip" value="46032"> <a href="#" onclick="getLocation()">Get Address</a>
</form>

You can see that I have a link which fires a function called “getLocation()”– below you'll find that function and the related code:

您可以看到我有一个链接,该链接会触发一个名为的函数“getLocation()”——您将在下面找到该函数和相关代码:

...
<script language="javascript">
function getLocation(){
  getAddressInfoByZip(document.forms[0].zip.value);
}

function response(obj){
  console.log(obj);
}
function getAddressInfoByZip(zip){
  if(zip.length >= 5 && typeof google != 'undefined'){
    var addr = {};
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': zip }, function(results, status){
      if (status == google.maps.GeocoderStatus.OK){
        if (results.length >= 1) {
      for (var ii = 0; ii < results[0].address_components.length; ii++){
        var street_number = route = street = city = state = zipcode = country = formatted_address = '';
        var types = results[0].address_components[ii].types.join(",");
        if (types == "street_number"){
          addr.street_number = results[0].address_components[ii].long_name;
        }
        if (types == "route" || types == "point_of_interest,establishment"){
          addr.route = results[0].address_components[ii].long_name;
        }
        if (types == "sublocality,political" || types == "locality,political" || types == "neighborhood,political" || types == "administrative_area_level_3,political"){
          addr.city = (city == '' || types == "locality,political") ? results[0].address_components[ii].long_name : city;
        }
        if (types == "administrative_area_level_1,political"){
          addr.state = results[0].address_components[ii].short_name;
        }
        if (types == "postal_code" || types == "postal_code_prefix,postal_code"){
          addr.zipcode = results[0].address_components[ii].long_name;
        }
        if (types == "country,political"){
          addr.country = results[0].address_components[ii].long_name;
        }
      }
      addr.success = true;
      for (name in addr){
          console.log('### google maps api ### ' + name + ': ' + addr[name] );
      }
      response(addr);
        } else {
          response({success:false});
        }
      } else {
        response({success:false});
      }
    });
  } else {
    response({success:false});
  }
}
</script>

...

Thats it – open up the console in Chrome and notice the output as you enter different zip codes.

就是这样 - 在 Chrome 中打开控制台并注意输入不同邮政编码时的输出。

get it from here: http://rickluna.com/wp/2012/09/using-the-google-maps-api-to-get-locations-from-zip-codes/

从这里获取:http: //rickluna.com/wp/2012/09/using-the-google-maps-api-to-get-locations-from-zip-codes/

回答by kaleazy

This is one way you could grab the address, city, state and/or zip from pretty much any location input, such as Santa Monica, CAor 90405. Keep in mind you can't always get all of these variables back unless you are very specific in your request.

这是您可以从几乎任何位置输入(例如Santa Monica, CA或 )获取地址、城市、州和/或邮编的一种方式90405。请记住,除非您的请求非常具体,否则您无法始终获得所有这些变量。

function getLocationInfo(){

    var location = $('#location').val();
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': location }, function (result, status) {

    var address = '';
    var streetNumber = '';
    var streetName = '';
    var cityName = '';
    var stateName = '';
    var zipCode = '';

    var addressComponent = result[0]['address_components'];

    // find street number

    var streetNumberQueryable = $.grep(addressComponent, function (x) {
        return $.inArray('street_number', x.types) != -1;
    });

    if (streetNumberQueryable.length) {
        streetNumber = streetNumberQueryable[0]['long_name'];
    }

    // find street name

    var streetNameQueryable = $.grep(addressComponent, function (x) {
        return $.inArray('route', x.types) != -1;
    });

    if (streetNameQueryable.length) {
        streetName = streetNameQueryable[0]['long_name'];
    }

    // find city data

    var cityQueryable = $.grep(addressComponent, function (x) {
        return $.inArray('locality', x.types) != -1;
    });

    if (cityQueryable.length) {
        cityName = cityQueryable[0]['long_name'];
    }

    // find state data

    var stateQueryable = $.grep(addressComponent, function (x) {
        return $.inArray('administrative_area_level_1', x.types) != -1;
    });

    if (stateQueryable.length) {
        stateName = stateQueryable[0]['long_name'];
    }

    // find zip data

    var zipQueryable = $.grep(addressComponent, function (x) {
        return $.inArray('postal_code', x.types) != -1;
    });

    if (zipQueryable.length) {
        zipCode = zipQueryable[0]['long_name'];
    }

    address = streetNumber + ' ' + streetName;

    console.log(address);
    console.log(cityName);
    console.log(stateName);
    console.log(zipCode);

    });

}

回答by SansWord

you need to know the mapping of zip_code and country,

你需要知道邮政编码和国家的映射,

I've found a github project for this:

我为此找到了一个 github 项目:

https://github.com/jgoodall/us-maps

https://github.com/jgoodall/us-maps

once you get json mapping by instruction, you can implement the function you want.

一旦你通过指令得到json映射,你就可以实现你想要的功能。

回答by u283863

Here is a nice geographic database API from the US government:
https://www.sba.gov/about-sba/sba-performance/sba-data-store/web-service-api/us-city-and-county-web-data-api#county-state

这是美国政府提供的一个不错的地理数据库 API:https:
//www.sba.gov/about-sba/sba-performance/sba-data-store/web-service-api/us-city-and-county- web-data-api#county-state

The API yields all counties and states information, however it doesn't seem to have ZIP codes included. Using Google Geocoding APImight be easier.

API 生成所有县和州的信息,但它似乎没有包含邮政编码。使用Google Geocoding API可能更容易。