Saltar al contenido

Analizando address_components en Google Maps al seleccionar autocompletar

Nuestro team de redactores ha pasado mucho tiempo buscando para darle espuestas a tus interrogantes, te regalamos la respuestas así que esperamos resultarte de gran apoyo.

Solución:

Solución general:

var address_components = results[0].address_components;
var components=; 
jQuery.each(address_components, function(k,v1) jQuery.each(v1.types, function(k2, v2)components[v2]=v1.long_name););

Ahora tu components Se ve como esto:

street_number: "1100", 
route: "E Hector St", 
locality: "Conshohocken", 
political: "United States", 
administrative_area_level_3: "Whitemarsh"…
administrative_area_level_1: "Pennsylvania"
administrative_area_level_2: "Montgomery"
administrative_area_level_3: "Whitemarsh"
country: "United States"
locality: "Conshohocken"
political: "United States"
postal_code: "19428"
route: "E Hector St"
street_number: "1100"

Que puedes consultar así:

components.country

Aquí está mi solución en mecanografiado

interface AddressComponent 
  long_name: string;
  short_name: string;
  types: Array;


interface Address 
  street_number?: string;
  street_name?: string;
  city?: string;
  state?: string;
  country?: string;
  postal_code?: string;


export class GoogleAddressParser 
  private address: Address = ;

  constructor(private address_components: Array) 
    this.parseAddress();
  

  private parseAddress() 
    if (!Array.isArray(this.address_components)) 
      throw Error('Address Components is not an array');
    

    if (!this.address_components.length) 
      throw Error('Address Components is empty');
    

    for (let i = 0; i < this.address_components.length; i++) 
      const component: AddressComponent = this.address_components[i];

      if (this.isStreetNumber(component)) 
        this.address.street_number = component.long_name;
      

      if (this.isStreetName(component)) 
        this.address.street_name = component.long_name;
      

      if (this.isCity(component)) 
        this.address.city = component.long_name;
      

      if (this.isCountry(component)) 
        this.address.country = component.long_name;
      

      if  (this.isState(component)) 
        this.address.state = component.long_name;
      

      if (this.isPostalCode(component)) 
        this.address.postal_code = component.long_name;
      
    
  

  private isStreetNumber(component: AddressComponent): boolean 
    return component.types.includes('street_number');
  

  private isStreetName(component: AddressComponent): boolean 
    return component.types.includes('route');
  

  private isCity(component): boolean 
    return component.types.includes('locality');
  

  private isState(component): boolean 
    return component.types.includes('administrative_area_level_1');
  

  private isCountry(component): boolean 
    return component.types.includes('country');
  

  private isPostalCode(component): boolean 
    return component.types.includes('postal_code');
  

  result(): Address 
    return this.address;
  

Uso:

const address = new GoogleAddressParser(results[0].address_components).result();

A continuación se muestra el código de trabajo completo:

$('#spot_address').autocomplete(
  // This bit uses the geocoder to fetch address values
  source: function(request, response) 
    geocoder.geocode( 'address': request.term , function(results, status) 
      response($.map(results, function(item) 
          // Get address_components
          for (var i = 0; i < item.address_components.length; i++)
          
            var addr = item.address_components[i];
            var getCountry;
            if (addr.types[0] == 'country') 
              getCountry = addr.long_name;
          
        return 
          label: item.formatted_address,
          value: item.formatted_address,
          latitude: item.geometry.location.lat(),
          longitude: item.geometry.location.lng(),
          country: getCountry
        
      ));
    )
  ,

  // This bit is executed upon selection of an address
  select: function(event, ui) 
    // Get values
    $('#spot_country').val(ui.item.country);
    $('#spot_lat').val(ui.item.latitude);
    $('#spot_lng').val(ui.item.longitude);
    var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
    marker.setPosition(location);
    map.setCenter(location);
  ,

  // Changes the current marker when autocomplete dropdown list is focused
  focus: function(event, ui) 
    var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
    marker.setPosition(location);
    map.setCenter(location);
  
);

Aquí puedes ver las reseñas y valoraciones de los lectores

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *