Created
September 26, 2017 14:51
-
-
Save hanipcode/3f6e99c8832e1ffe8ee59264bd4c77ac to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| const qs = require('qs'); | |
| // import cancelable-fetch | |
| const fetch = require('react-native-cancelable-fetch'); | |
| function getPredictionList(searchQuery, key) { | |
| const queryString = qs.stringify({ | |
| input: searchQuery, | |
| type: 'geocode', | |
| key | |
| }); | |
| const uri = `https://maps.googleapis.com/maps/api/place/autocomplete/json?${queryString}`; | |
| //beri tagging prediction | |
| return fetch(uri, null, 'prediction').then(response => response.json()); | |
| } | |
| function getPlaceDetails(placeId, key) { | |
| const queryString = qs.stringify({ | |
| placeid: placeId, | |
| key | |
| }); | |
| const uri = `https://maps.googleapis.com/maps/api/place/details/json?${queryString}`; | |
| //beri tagging placeDetail | |
| return fetch(uri, null, 'placeDetail').then(response => response.json()); | |
| } | |
| export function getPredictionWithDetail(searchQuery, key) { | |
| //abort semua fetch dengan tag prediction dan place detail sebelum melakukan fetch | |
| //nice isn't it ? | |
| fetch.abort('prediction'); | |
| fetch.abort('placeDetail'); | |
| return getPredictionList(searchQuery, key) | |
| .then(result => { | |
| const predictions = result.predictions; | |
| const predictionsPromise = predictions.map(prediction => | |
| getPlaceDetails(prediction.place_id, key) | |
| ); | |
| return Promise.all(predictionsPromise); | |
| }) | |
| .then(data => { | |
| console.log(data); | |
| const predictionDetails = data.map(predictionItem => ({ | |
| name: predictionItem.result.name, | |
| formatted_address: predictionItem.result.formatted_address, | |
| geometry: predictionItem.result.geometry, | |
| placeId: predictionItem.result.place_id | |
| })); | |
| return predictionDetails; | |
| }) | |
| .catch(err => { | |
| console.log(err.toString()); | |
| return err; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment