Last active
May 30, 2018 15:44
-
-
Save sharynneazhar/770edfc360a5a4ccbf1c337d54d4160e to your computer and use it in GitHub Desktop.
Google Place Autocomplete API - Select First Suggestion on Enter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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