Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the place_id of a city using google places autocomplete

I'm using an input field with google places autocomplete. I' ve set autocomplete to predict only cities but I'm stuggling to find a simple way to get the unique place_id of the selected city. I don't want to use it with google maps. I need it just to identify with a unique value the selected city.. Thanks in advance..

Here's my JS:

<script src="maps.googleapis.com/maps/api/js?libraries=places"; type="text/javascript"></script>
<script type="text/javascript">
function initialize() { 
  var options = { types: ['(cities)'] };
  var input = document.getElementById('searchCity');
  var autocomplete = new google.maps.places.Autocomplete(input,options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

And here's my PHP:

<form method="GET" action=<?php echo $_SERVER['PHP_SELF'];?>>
<input id="searchCity" type="text" size="50" 
  placeholder="Enter a City" autocomplete="on" name="city">
<br>
<?php if (!empty($_GET['city']) ) {
  echo $_GET['city'];
} else {
  echo "not set";
}
unset($_GET['city']); ?>
</form>
<!-- Here I would like to show the place_id of the selected city-->
</div>
like image 769
maragos Avatar asked Mar 16 '23 19:03

maragos


1 Answers

You don't need PHP to display the place details. You just need a Javascript event handler for place_changed.

E.g. add this code to your initialize function:

google.maps.event.addListener(autocomplete, 'place_changed', function() {
  var place = autocomplete.getPlace();
  var form = input.parentElement;
  form.appendChild(document.createTextNode("Place ID is " + place.place_id));
});

These samples from Google's docs contain complete examples of using the place_changed event. They're worth looking at:

  • https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete
  • https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder
like image 64
spiv Avatar answered May 13 '23 02:05

spiv