7

Ho trovato il codice su questo sito per ottenere lo stato da un codice postale, ma ho anche bisogno di ottenere il nome della città.Ottieni nome città da codice postale google geocoding

Ecco il mio codice per ottenere lo stato: (Nota Io uso anche 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

Mi potete condividere gli altri codici di jQuery per ottenere il nome del luogo con zip code.Io sono anche in cerca di esso ...... – Techy

risposta

8

Basta aggiungere result[0]['address_components'][1]['long_name']

Quindi sarebbe

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

Sei il totale MAAAAN !!!! Molte grazie!! – boruchsiper

+0

Hehe .. Anytime :) –

+2

Fare attenzione a utilizzare gli indici dei componenti_indirizzo in quanto NON SONO COERENTI! –

6

Ho riscritto sopra soluzione per guardare più elegante:

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

Sembra che ci siano alcuni problemi con google geocode per trovare città dal codice postale. Ad esempio chiedendo "59650, Francia" restituisce Wattrelos invece di Villeneuve d'Ascq. Lo stesso vale per (poche) altre città testate in Francia e Germania. non so perché, non so come risolverlo –

6

Di seguito è riportato il codice per controllare il nome della città da Zipcode utilizzando 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

non hai usato jquery come op ha chiesto, questo è esattamente quello che volevo +1 – Dheeraj

+0

Scusa, non ottenere. – Nimesh

+0

ho detto che il tuo codice mi è stato utile – Dheeraj

0

Sono abbastanza generoso per fornire il modulo esatto ho arrotolato a fare questo per noi. Esso restituisce un oggetto come ad esempio:

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

e può essere chiamato con il codice: let test = new ZipCodeDeconstructor().deconstruct('20009');

Questo è scritto in TypeScript (salire su quel treno) e utilizzato in node.js (si dovrebbe già essere su quel treno .

Se non si dispone di request-promise ancora, eseguire npm i request-promise --save ed essere che la configurazione dattiloscritto consente per le async/await parole chiave da utilizzare.

Questo è fondamentalmente l'uso di tutto "nuovo" al momento in cui è stato scritto, quindi dovrebbe essere abbastanza utile per un po 'di tempo a venire.

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

Le interfacce in alto dovrebbe aiutare a lungo il modo di comprendere ciò che viene restituito e ciò che dovrebbe essere passato in.