Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active October 19, 2022 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmenta/c828e0b7636930ff977856ad32945894 to your computer and use it in GitHub Desktop.
Save sturmenta/c828e0b7636930ff977856ad32945894 to your computer and use it in GitHub Desktop.
get google maps place by autocomplete
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