Javascript 从邮政编码谷歌地理编码获取城市名称

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

Get City Name from Zip Code google geocoding

javascriptjquerygoogle-maps-api-3google-geocoding-api

提问by boruchsiper

I've found code on this site to get the sate from a zipcode, but I also need to get the city name.

我在这个网站上找到了从邮政编码中获取状态的代码,但我还需要获取城市名称。

Here is my code for getting the state: (Note I also use jQuery)

这是我获取状态的代码:(注意我也使用 jQuery)

var geocoder = new google.maps.Geocoder();

    $('.zip').bind('change focusout', function () {
        var $this = $(this);
        if ($this.val().length == 5) {
            geocoder.geocode({ 'address': $this.val() }, function (result, status) {
                var state = "N/A";
                //start loop to get state from zip
                for (var component in result[0]['address_components']) {
                    for (var i in result[0]['address_components'][component]['types']) {
                        if (result[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
                            state = result[0]['address_components'][component]['short_name'];
                            // do stuff with the state here!
                            $this.closest('tr').find('select').val(state);
                        }
                    }
                }
            });
        }
    });  

回答by Marco Johannesen

Just add result[0]['address_components'][1]['long_name']

只需添加 result[0]['address_components'][1]['long_name']

So it would be

所以它会

var geocoder = new google.maps.Geocoder();

$('.zip').bind('change focusout', function () {
    var $this = $(this);
    if ($this.val().length == 5) {
        geocoder.geocode({ 'address': $this.val() }, function (result, status) {
            var state = "N/A";
            var city = "N/A";
            //start loop to get state from zip
            for (var component in result[0]['address_components']) {
                for (var i in result[0]['address_components'][component]['types']) {
                    if (result[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
                        state = result[0]['address_components'][component]['short_name'];
                        // do stuff with the state here!
                        $this.closest('tr').find('select').val(state);
                        // get city name
                        city = result[0]['address_components'][1]['long_name'];
                        // Insert city name into some input box
                        $this.closest('tr').find('.city').val(city);
                    }
                }
            }
        });
    }
});  

回答by cryss

I've rewritten above solution to look more elegant:

我已经重写了上面的解决方案,看起来更优雅:

var zipCode = '48201';
var country = 'United States';               

var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': zipCode + ',' + country }, function (result, status) {

    var stateName = '';
    var cityName = '';

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

    // 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'];

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

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

回答by Nimesh

Below is code to check City name from Zipcode using googleapis.

下面是使用 googleapis 从邮政编码检查城市名称的代码。

<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Geocoding service</title>    
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>      
<script>    
        var geocoder;
        var map;        
        function codeAddress() {
            geocoder = new google.maps.Geocoder();
            var address = document.getElementById('address').value;
            geocoder.geocode({ 'address': address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {                       

                    for (var component in results[0]['address_components']) {
                        for (var i in results[0]['address_components'][component]['types']) {
                            if (results[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
                                state = results[0]['address_components'][component]['long_name'];
                                alert(results[0]['address_components'][1]['long_name'] + ' , '  + state);
                            }
                        }
                    }                                           
                } else {
                    alert('Invalid Zipcode');
                }
            });
        }         

    </script>
  </head>
  <body>
    <div id="panel">
      <input id="address" type="textbox" value="Sydney, NSW">
      <input type="button" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

回答by Augie Gardner

I'm generous enough to provide the exact module I rolled to do this for us. It returns an object such as:

我很慷慨地提供我为我们做这件事的确切模块。它返回一个对象,例如:

{ 
  country : { long_name : "someString", short_name : "someStrong" },
  city : { long_name : "someString", short_name : "someString" },
  state : { long_name : "someString", short_name : "someString" }
}

and can be called using the code : let test = new ZipCodeDeconstructor().deconstruct('20009');

并且可以使用代码调用: let test = new ZipCodeDeconstructor().deconstruct('20009');

This is written in TypeScript(get on that train) and used in node.js(you should already be on that train.

这是写在TypeScript(上那列火车)并用于node.js(你应该已经在那列火车上。

If you don't have request-promiseyet, run npm i request-promise --saveand be sure your TypeScript configuration allows for the async/awaitkeywords to be used.

如果您还request-promise没有,请运行npm i request-promise --save并确保您的 TypeScript 配置允许使用async/await关键字。

This is basically using everything "new" as of the time this has been written, so it should be quite useful for some time to come.

这基本上是使用截至撰写本文时的所有“新”内容,因此在未来一段时间内它应该非常有用。

let rp = require('request-promise');
enum IGoogleMapResultType {
  COUNTRY = <any>'country',
  LOCALITY = <any>'locality',
  SUBLOCALITY_LEVEL_1 = <any>'sublocality_level_1',
  ADMINISTRATIVE_AREA_LEVEL_1 = <any>'administrative_area_level_1',
    // These may be used later, don't delete them, they're for reference
  POSTAL_CODE = <any>'postal_code',
  NEIGHBORHOOD = <any>'neighborhood',
  POLITICAL = <any>'political',
  ADMINISTRATIVE_AREA_LEVEL_2 = <any>'administrative_area_level_2',
  ADMINISTRATIVE_AREA_LEVEL_3 = <any>'administrative_area_level_3'
}
interface IGoogleMapResult {
  address_components : {
    long_name? : string
    short_name? : string
    types : IGoogleMapResultType[]
  }[],
  formatted_address : string,
  geometry: any,
  place_id: string,
  types: IGoogleMapResultType[]
}
type IGoogleMapResults = any[];
type ZipCodeDeconstructorProperty = {
  long_name: string,
  short_name: string
}
// What we return from this component
export type ZipCodeDeconstructorResponse = {
  city: ZipCodeDeconstructorProperty,
  state: ZipCodeDeconstructorProperty,
  country: ZipCodeDeconstructorProperty
}
export class ZipCodeDeconstructor {
  static apiUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=";
  constructor() {}
  // main entry point, deconstruct a 5 digit zip into city, state, zip into the corresponding properties
  async deconstruct(zip):Promise<ZipCodeDeconstructorResponse> {
    let response:any = await this._makeCall(zip);
    let firstResult = response.results[0];
    let returnObject = {
      city :  this._extractCity(firstResult),
      state : this._extractState(firstResult),
      country : this._extractCountry(firstResult)
    };
    console.log("[Zip Code Deconstructor] returning: ", returnObject);
    return returnObject;
  }
  private _createZipcodeUrl(zip) {
    return ZipCodeDeconstructor.apiUrl + zip + '&sensor=true';
  }
  private async _makeCall(zip) {
    return await rp({uri : this._createZipcodeUrl(zip), json : true });
  }
  private _extractOfTypeFromResult(typesArray:IGoogleMapResultType[], result:IGoogleMapResult) {
    for(let i = 0; i < result.address_components.length; i++) {
      let addressComponentAtIndex = result.address_components[i];
      let type:IGoogleMapResultType = addressComponentAtIndex.types[0];
      if(typesArray.indexOf(type) !== -1) {
        return {
          long_name : addressComponentAtIndex.long_name,
          short_name : addressComponentAtIndex.short_name
        }
      }
    }
  }
  private _extractCity(result:IGoogleMapResult) {
    return this._extractOfTypeFromResult([IGoogleMapResultType.SUBLOCALITY_LEVEL_1, 
      IGoogleMapResultType.LOCALITY], result)
  }
  private _extractState(result:IGoogleMapResult) {
    return this._extractOfTypeFromResult([IGoogleMapResultType.ADMINISTRATIVE_AREA_LEVEL_1], result);
  }
  private _extractCountry(result:IGoogleMapResult) {
    return this._extractOfTypeFromResult([IGoogleMapResultType.COUNTRY], result);
  }
}
// let test = new ZipCodeDeconstructor().deconstruct('20009');

The interfaces at the top should help you along the way of understanding what gets returned and what should be passed in.

顶部的接口应该可以帮助您了解返回的内容和应该传入的内容。