Search code examples
reactjsgoogle-places-autocomplete

How to get country, state and city name globally from google auto complete service


In one of my front end (react) requirement I need to get globally country name, state name, city name, placeId, Latitude and longitude once a place gets selected from the autocomplete suggestion. I'm able to get city name (from name key),placeId, latitude and longitude from geometry key of the response. I'm using this google script using place api service => ---------------------------------- this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current, {"types": ['(cities)']}); this.autocomplete.addListener('place_changed', this.handlePlaceChanged); ----------------------------------- And in handlePlaceChanged function I'm getting following response =>>

 {"address_components":[{"long_name":"Bengaluru","short_name":"Bengaluru","types": 

["locality","political"]},{"long_name":"Bangalore Urban","short_name":"Bangalore Urban","types":["administrative_area_level_2","political"]}, {"long_name":"Karnataka","short_name":"KA","types": ["administrative_area_level_1","political"]},{"long_name":"India","short_name":"IN","types": ["country","political"]}],"adr_address":"Bengaluru, Karnataka, India","formatted_address":"Bengaluru, Karnataka, India","geometry": {"location":{"lat":12.9715987,"lng":77.5945627},"viewport":{"south":12.7342888,"west":77.3791981,"north":13.173706,"east":77.8826809}},"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png","id":"0862832923832bfb1e46cbe843cdaa03a9ee8aa1","name":"Bengaluru","photos":[{"height":405,"html_attributions":["https://maps.google.com/maps/contrib/113170619945048632846\">abdusamad k"],"width":720},{"height":385,"html_attributions":["https://maps.google.com/maps/contrib/105596602452460947497\">Rince T R"],"width":796},{"height":2340,"html_attributions":["https://maps.google.com/maps/contrib/107994729306954910118\">Riju Pal"],"width":4160},{"height":315,"html_attributions":["https://maps.google.com/maps/contrib/101926288772104749853\">Dipendra Bist"],"width":534},{"height":2592,"html_attributions":["https://maps.google.com/maps/contrib/100418682723295961842\">Achyuth rupavatharam"],"width":1944},{"height":424,"html_attributions":["https://maps.google.com/maps/contrib/118332000005283281641\">Jerin Asher Sojan"],"width":640},{"height":2448,"html_attributions":["https://maps.google.com/maps/contrib/102738049583390423145\">DEBAJYOTI GHATAK"],"width":3264},{"height":789,"html_attributions":["https://maps.google.com/maps/contrib/109699434808207248873\">nitin kumar"],"width":1080},{"height":3024,"html_attributions":["https://maps.google.com/maps/contrib/109460450047584922534\">Blue Dares"],"width":4032},{"height":738,"html_attributions":["https://maps.google.com/maps/contrib/116995855942077255039\">Chelsy Halder"],"width":1599}],"place_id":"ChIJbU60yXAWrjsR4E9-UejD3_g","reference":"ChIJbU60yXAWrjsR4E9-UejD3_g","scope":"GOOGLE","types":["locality","political"],"url":"https://maps.google.com/?q=Bengaluru,+Karnataka,+India&ftid=0x3bae1670c9b44e6d:0xf8dfc3e8517e4fe0","utc_offset":330,"vicinity":"Bengaluru","html_attributions":[],"utc_offset_minutes":330}

=============================================================

I need guidance on how should I get Country name, State name, City name globally

Solution

  • Well I googled for some solution and ultimately made my own solution and this worked for me. Its the main part of the solution code :

    compIsType(t, s) { 
        for(let z = 0; z < t.length; ++z) 
           if(t[z] == s)
          return true;
    
        return false;
    }
    
      handlePlaceChanged(){      
    const place = this.autocomplete.getPlace();
    //console.log(" from google auto complete place===>",place);
    let lat, lng, addrSel, placeName, placeId =''; 
    let country, state, city =null;  
    if(place.geometry!==undefined ){
      const plcGeom = place.geometry;
      if(plcGeom.location!==undefined){
        lat = plcGeom.location ? plcGeom.location.lat():'';
        lng = plcGeom.location ? plcGeom.location.lng():'';
      }      
    }   
    
    addrSel  = place.formatted_address!==undefined?place.formatted_address:"";
    placeName  = place.name!==undefined?place.name:"";
    placeId = place.place_id!==undefined?place.place_id:"";
    
    if(place.address_components!==undefined){
      let addrComp = place.address_components;
      for(let i = 0; i < addrComp.length; ++i)
      {
        var typ = addrComp[i].types;
        if(this.compIsType(typ, 'administrative_area_level_1'))
            state = addrComp[i].long_name; //store the state
        else if(this.compIsType(typ, 'locality'))
            city = addrComp[i].long_name; //store the city
        else if(this.compIsType(typ, 'country'))
          country = addrComp[i].long_name; //store the country        
    
        //we can break early if we find all three data
        if(state != null && city != null && country != null) break;
      }
      
      
    
    
    }
    
    let nameData = "";
      if(this.props.showKey!==undefined ){
    
        
        if(this.props.showKey=="CITY"){
          nameData = city;
        }
        else if(this.props.showKey=="STATE"){
          nameData = state;
        }
        else if(this.props.showKey=="COUNTRY"){
          nameData = country;
        }
         else if(this.props.showKey=="PLACE_NAME"){
          nameData = country;
        }
        else if(this.props.showKey=="FORMATTED_ADDRESS"){
          nameData = addrSel;
        }
         else if(this.props.showKey=="PLACE_ID"){
          nameData = placeId;
        }
        else{
          nameData = addrSel;
        }
       
      }else{
        
        nameData = addrSel;
      }
    
      
    
      if(this.props.removeTextFlag!==undefined && this.props.removeTextFlag=="YES" ){
        nameData = "";
      }
    
    let stateResp = {
      'lat':lat,
      'lng': lng,
      'formattedAddress':addrSel, 
      'placeName': placeName,
      'placeId': placeId,
      'city':city,
      'state':state,
      'country':country,
      'textboxtext':nameData
    };
    this.setState(stateResp,()=>{
     this.props.selectedGoogleDataInfo!==undefined && this.props.selectedGoogleDataInfo(stateResp);    
    });
    //console.log(place);
    //console.log("==lat==>", lat," ==lng===>",lng, "==addrSel==>",addrSel);
    //this.props.onPlaceLoaded(place);
       }