Autocomplete only a place name using the Google places API

I have successfully set up auto-completion for the Google Places API using

var input = document.getElementById('place_name');
var autocomplete = new google.maps.places.Autocomplete(input);

But this automatically fills the place_name text field with the full address, such as "ABC, Some Street, Washington, WA, United States" But I want to fill the text field with only the place name, for example. ABC in my case. How can i do this?

I tried

google.maps.event.addListener(autocomplete, 'place_changed', function () {
    var place = autocomplete.getPlace();

    $('#place_name').val(place.name);
});

but did nothing. Help me please...

+4
source share
2 answers

, . , , . ,

input.value=input.value.split(',')[0]; 

place_changedhttp://jsfiddle.net/9RkM9/


, Google Maps () : enter image description here

Google , , , , .

.pac-item : "Los":

<div class="pac-item">
    <span class="pac-item-query"><span class="pac-matched">Los</span>
    Altos</span><span>CA, United States</span>
</div>

CA United States , . , .pac-item node, . , , input keyup. , , :

input.onkeyup = function(e) {
   setTimeout(function() {
      var places = document.querySelectorAll('.pac-item');      
      for (var i=0;i<places.length;i++) {
         var place = places[i];
         //get the icon
         var pac_icon = place.querySelector('.pac-icon').outerHTML;
         //get the mathed name only, including markup for precise match, loke "Los" in bold 
         var place_name_reduced = place.querySelector('.pac-item-query').outerHTML;
         place.innerHTML = pac_icon + place_name_reduced;
      }
   }, 150);
}

http://jsfiddle.net/8SGvR/

+7

. . , .

place.address_components

, , :

console.log(place.address_components);

,

$('#place_name').val(place.address_components[0].long_name);
+2

Source: https://habr.com/ru/post/1530838/


All Articles