7

我在這個網站上發現了代碼來獲取郵編的狀態,但我也需要獲取城市名稱。從郵政編碼獲取城市名稱谷歌地理編碼

這裏是我得到的國家代碼: (注意我也使用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); 
         } 
        } 
       } 
      }); 
     } 
    }); 
+0

你能分享我的其他的jQuery代碼獲得使用拉鍊的地方的名字code.I也在尋找它...... – Techy 2013-01-01 13:07:42

回答

8

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

因此,這將是

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); 
        } 
       } 
      } 
     }); 
    } 
}); 
+1

你是總MAAAAN !!!!非常感謝!! – boruchsiper 2012-04-26 20:46:03

+0

呵呵..任何時候:) – 2012-04-26 21:26:38

+2

小心使用address_components的索引,因爲它們不一致! – 2015-01-12 08:24:41

6

我已經重寫以上解決方案看起來更優雅:

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']; 
     } 
    } 
}); 
+1

看起來像谷歌地理編碼有一些問題,從郵編查找城市。例如,要求「59650,法國」返回Wattrelos而不是Villeneuve d'Ascq。在法國和德國的其他幾個城市也是如此。不知道爲什麼,不知道如何解決它。 – 2014-04-27 10:48:17

6

以下是使用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> 
+0

你一直沒有使用jquery like op問,這正是我想要的+1 – Dheeraj 2015-08-31 14:52:36

+0

對不起,沒有得到。 – Nimesh 2015-09-01 05:09:21

+0

我說你的代碼對我有用 – Dheeraj 2015-09-01 06:42:28

0

我很慷慨,足以提供確切的模塊,我滾動來爲我們做這個。它返回一個對象,如:

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

,並可以使用代碼調用:let test = new ZipCodeDeconstructor().deconstruct('20009');

這是寫在TypeScript(試驗的人),並在node.js使用(你應該已經對列車。

如果沒有request-promise做的是,運行npm i request-promise --save並確保您的打字稿配置允許使用的async/await關鍵字。

這個基本上是在寫這個時候使用「new」的所有東西,所以它在一段時間內應該是非常有用的。

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'); 

頂部的接口應能幫助你走好什麼獲取返回,什麼也應傳遞的理解方式。

相關問題