Google Places Javascript Api Query for Places (Find Places by Name)

August 24, 2018
PlaceService.findPlaceFromQuery

Get API Key

Goto Google Cloud Api Console -> Library -> Places API and click Enable. You might want to enable Maps JavaScript API as well.

Goto Google Cloud Api Console -> Credentials -> Create credentials -> API key. You probably want to apply restriction using HTTP referrers (websites). In the Accept requests from these HTTP referrers (websites), you can use some of the following example:

  • *localhost:8088/*
  • *.mydomain.com/*
  • *.myappid.appspot.com/*

Copy the API Key.

NOTE: You can try follow Get Started wizard on Google’s page, but I haven’t gone through that before.

Include Google Maps Javascript

<div id="map" style="height: 300px;"></div>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
  type="text/javascript"></script>

<script>
function initMap() {

}
</script>

Using PlacesService findPlaceFromQuery

const mapCenter = new google.maps.LatLng(-33.8617374,151.2021291)

const map = new google.maps.Map(document.getElementById('map'), {
  center: mapCenter,
  zoom: 15
})

const placeService = new google.maps.places.PlacesService(map)

const request = {
  query: 'japan',
  fields: ['place_id', 'name', 'formatted_address', 'icon', 'geometry'],
}

placeService.findPlaceFromQuery(request, (results, status) => {
  if (status == google.maps.places.PlacesServiceStatus.OK) {

    results.forEach((item) => {
      console.log(item)
      // place_id, name, formatted_address, geometry.location, icon
    });
  }
})

NOTE: Refer to PlacesService.findPlaceFromQuery

findPlaceFromQuery only works if the full name is given (e.g. Japan, not Ja or Jap). To use partial name autocomplete feature, use Autocomplete.getPlacePredictions.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.