Skip to content

Instantly share code, notes, and snippets.

@sharynneazhar
Last active May 30, 2018 15:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharynneazhar/770edfc360a5a4ccbf1c337d54d4160e to your computer and use it in GitHub Desktop.
Save sharynneazhar/770edfc360a5a4ccbf1c337d54d4160e to your computer and use it in GitHub Desktop.
Google Place Autocomplete API - Select First Suggestion on Enter
import React, { Component } from 'react';
export default class LocationSearch extends Component {
componentDidMount() {
const input = document.getElementById("location");
const options = { types: [ "(regions)" ] };
this.locationSearch = new google.maps.places.Autocomplete(input, options);
this.locationSearch.addListener("place_changed", this.handleLocationSearch);
}
render() {
return <input type="text" id="location" placeholder="Location (Brooklyn, NY, USA)" />
}
handleLocationSearch = () => {
const location = this.locationSearch.getPlace();
let locationObj = { city: [], state: [], country: [] };
if (location.address_components) {
locationObj = parseGooglePlaces(location);
this.props.dispatch(addLocationFilter(locationObj));
return;
}
const autocompleteService = new google.maps.places.AutocompleteService();
autocompleteService.getPlacePredictions({
input: location.name,
types: [ "(regions)" ]
}, (predictions, status) => {
if (status == google.maps.places.PlacesServiceStatus.OK) {
const placesService = new google.maps.places.PlacesService(document.createElement('div'));
placesService.getDetails({
placeId: predictions[0].place_id
}, (place, status) => {
if (status == google.maps.places.PlacesServiceStatus.OK) {
locationObj = parseGooglePlaces(place);
this.props.dispatch(addLocationFilter(locationObj));
}
});
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment