Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default value for a Google places API auto complete textbox

I'm working on a page close enough to the one in google samples https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform and it works fine.

However I need to add one more feature is to set the value of the autocomplete by default to be the current user city.

I'm using the following code to get the city and the country of the logged in user using geolocation API in HTML5. However the challenge is to make the autocomplete accept this value as it's default value. When I try to put the value in the textbox directly the autocomplete consider it as a wrong value.

navigator.geolocation.getCurrentPosition(function(pos) {
   var currentLocation = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
   var geocoder = new google.maps.Geocoder();
   var city = "";
   var country = "";
   geocoder.geocode({'latLng': currentLocation}, function(results, status, from) {
      if (status == google.maps.GeocoderStatus.OK) {
         if (results[1]) {
            for (var i = 0; i < results[0].address_components.length; i++) {
               for (var b = 0; b < results[0].address_components[i].types.length; b++) {
                  if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                     city = results[0].address_components[i];
                     break;
                  }
                  if (results[0].address_components[i].types[b] == "country") {
                     country = results[0].address_components[i];
                     break;
                  }
               }
            }
            var fromDefault = city.long_name + " - " + country.long_name;
            $('#address-from').val(fromDefault);
         }
      }
   });
}, 
function(error) {                    
   alert('Unable to get location: ' + error.message);
}, options);

Any idea how to manually fill in the default value for the autocomplete places textbox?

like image 568
Joseph Wahba Avatar asked Feb 15 '16 06:02

Joseph Wahba


People also ask

How do I limit Google autocomplete results to state only?

Location restrict You may also restrict results to the region defined by location and a radius parameter, by adding the strictbounds parameter. This instructs the Place Autocomplete service to return only results within that region.

How do I get lat long on Google autocomplete?

Getting latitude and longitude Wen the user has selected a place we can get the latitude and longitude by calling lat() and lng() on the place object.


1 Answers

I had the same requirement of setting the initial location when the Map initally loads.

This is how I did it:

As Jon Hannah mentioned, I used the Autocomplete Service to get the prediction, then used the first prediction to get the Place (using place_id). Populated the Autocompelete input with my default location string. Finally triggered the place_change event.

  this.input.nativeElement.value = this.testLocationStr;

  let autocompleteService = new google.maps.places.AutocompleteService();
  let request = {input: this.testLocationStr};
  autocompleteService.getPlacePredictions(request, (predictionsArr, placesServiceStatus) => {
    console.log('getting place predictions :: predictionsArr = ', predictionsArr, '\n',
      'placesServiceStatus = ', placesServiceStatus);

    let placeRequest = {placeId: predictionsArr[0].place_id};
    let placeService = new google.maps.places.PlacesService(this.mapObj);
    placeService.getDetails(placeRequest, (placeResult, placeServiceStatus) => {
      console.log('placeService :: placeResult = ', placeResult, '\n',
        'placeServiceStatus = ', placeServiceStatus);

      this._handlePlaceChange(placeResult);

    });
  });

Plunker: https://plnkr.co/edit/9oN6Kg?p=preview

like image 120
Ram P Avatar answered Oct 21 '22 00:10

Ram P