Last active
October 19, 2022 11:31
-
-
Save sturmenta/c828e0b7636930ff977856ad32945894 to your computer and use it in GitHub Desktop.
get google maps place by autocomplete
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
import Qs from 'qs'; | |
import {GOOGLE_MAPS_API_KEY} from 'react-native-dotenv'; | |
export const getGoogleMapsPlaceByAutocomplete = ( | |
place: string, | |
): Promise<{ | |
data?: { | |
predictions: Array<{ | |
description: string; | |
place_id: string; | |
types: Array<string>; | |
}>; | |
}; | |
error?: string; | |
}> => | |
new Promise(res => { | |
try { | |
const request = new XMLHttpRequest(); | |
request.open( | |
'GET', | |
`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=` + | |
encodeURIComponent(place) + | |
'&' + | |
Qs.stringify({ | |
key: GOOGLE_MAPS_API_KEY, | |
language: 'en', | |
types: 'geocode', | |
}), | |
); | |
request.send(); | |
request.onreadystatechange = () => { | |
if (request.readyState !== 4) return; | |
if (request.status !== 200) | |
res({error: 'status: ' + request.status.toString()}); | |
const responseJSON = JSON.parse(request.responseText); | |
if (responseJSON.status === 'ZERO_RESULTS') res({data: undefined}); | |
if (responseJSON.status === 'OK') res({data: responseJSON}); | |
res({error: responseJSON.status}); | |
}; | |
} catch (e) { | |
console.warn('google places autocomplete catch: ' + e); | |
res({error: String(e)}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment