Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New places api #943

Merged
merged 10 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions GooglePlacesAutocomplete.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,8 @@ interface GooglePlaceData {
interface Point {
lat: number;
lng: number;
latitude: number;
longitude: number;
}

interface AddressComponent {
Expand Down Expand Up @@ -323,6 +325,11 @@ interface GooglePlaceDetail {
url: string;
utc_offset: number;
vicinity: string;
// New Places API parameters
addressComponents: AddressComponent[];
adrFormatAddress: string;
formattedAddress: string;
location: Point;
}

/** @see https://developers.google.com/places/web-service/autocomplete */
Expand Down Expand Up @@ -431,6 +438,8 @@ interface GooglePlacesAutocompleteProps {
/** text input props */
textInputProps?: TextInputProps | Object;
timeout?: number;
isNewPlacesAPI?: boolean;
fields?: string;
}

export type GooglePlacesAutocompleteRef = {
Expand Down
113 changes: 91 additions & 22 deletions GooglePlacesAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import debounce from 'lodash.debounce';
import PropTypes from 'prop-types';
import Qs from 'qs';
import { v4 as uuidv4 } from 'uuid';
import React, {
forwardRef,
useMemo,
Expand Down Expand Up @@ -159,7 +160,7 @@ export const GooglePlacesAutocomplete = forwardRef((props, ref) => {
const [listLoaderDisplayed, setListLoaderDisplayed] = useState(false);

const inputRef = useRef();

const [sessionToken, setSessionToken] = useState(uuidv4());
useEffect(() => {
setUrl(getRequestUrl(props.requestUrl));
}, [getRequestUrl, props.requestUrl]);
Expand Down Expand Up @@ -281,10 +282,14 @@ export const GooglePlacesAutocomplete = forwardRef((props, ref) => {

if (request.status === 200) {
const responseJSON = JSON.parse(request.responseText);

if (responseJSON.status === 'OK') {
if (
responseJSON.status === 'OK' ||
(props.isNewPlacesAPI && responseJSON.id === rowData.place_id)
) {
// if (_isMounted === true) {
const details = responseJSON.result;
const details = props.isNewPlacesAPI
? responseJSON
: responseJSON.result;
_disableRowLoaders();
_onBlur();

Expand Down Expand Up @@ -322,16 +327,29 @@ export const GooglePlacesAutocomplete = forwardRef((props, ref) => {
}
};

request.open(
'GET',
`${url}/place/details/json?` +
Qs.stringify({
key: props.query.key,
placeid: rowData.place_id,
language: props.query.language,
...props.GooglePlacesDetailsQuery,
}),
);
if (props.isNewPlacesAPI) {
request.open(
'GET',
`${url}/v1/places/${rowData.place_id}?` +
Qs.stringify({
key: props.query.key,
sessionToken,
fields: props.fields,
}),
);
setSessionToken(uuidv4());
} else {
request.open(
'GET',
`${url}/place/details/json?` +
Qs.stringify({
key: props.query.key,
placeid: rowData.place_id,
language: props.query.language,
...props.GooglePlacesDetailsQuery,
}),
);
}

request.withCredentials = requestShouldUseWithCredentials();
setRequestHeaders(request, getRequestHeaders(props.requestUrl));
Expand Down Expand Up @@ -419,6 +437,29 @@ export const GooglePlacesAutocomplete = forwardRef((props, ref) => {
return results;
};

const _filterResultsByPlacePredictions = (unfilteredResults) => {
const results = [];
for (let i = 0; i < unfilteredResults.length; i++) {
if (unfilteredResults[i].placePrediction) {
results.push({
description: unfilteredResults[i].placePrediction.text?.text,
place_id: unfilteredResults[i].placePrediction.placeId,
reference: unfilteredResults[i].placePrediction.placeId,
structured_formatting: {
main_text:
unfilteredResults[i].placePrediction.structuredFormat?.mainText
?.text,
secondary_text:
unfilteredResults[i].placePrediction.structuredFormat
?.secondaryText?.text,
},
types: unfilteredResults[i].placePrediction.types ?? [],
});
}
}
return results;
};

const _requestNearby = (latitude, longitude) => {
_abortRequests();

Expand Down Expand Up @@ -524,6 +565,7 @@ export const GooglePlacesAutocomplete = forwardRef((props, ref) => {
setListLoaderDisplayed(false);
if (request.status === 200) {
const responseJSON = JSON.parse(request.responseText);

if (typeof responseJSON.predictions !== 'undefined') {
// if (_isMounted === true) {
const results =
Expand All @@ -538,6 +580,14 @@ export const GooglePlacesAutocomplete = forwardRef((props, ref) => {
setDataSource(buildRowsFromResults(results, text));
// }
}
if (typeof responseJSON.suggestions !== 'undefined') {
const results = _filterResultsByPlacePredictions(
responseJSON.suggestions,
);

_results = results;
setDataSource(buildRowsFromResults(results, text));
}
if (typeof responseJSON.error_message !== 'undefined') {
if (!props.onFail)
console.warn(
Expand All @@ -556,18 +606,33 @@ export const GooglePlacesAutocomplete = forwardRef((props, ref) => {
setStateText(props.preProcess(text));
}

request.open(
'GET',
`${url}/place/autocomplete/json?input=` +
encodeURIComponent(text) +
'&' +
Qs.stringify(props.query),
);
if (props.isNewPlacesAPI) {
request.open('POST', `${url}/v1/places:autocomplete`);
rojiphil marked this conversation as resolved.
Show resolved Hide resolved
} else {
request.open(
'GET',
`${url}/place/autocomplete/json?input=` +
encodeURIComponent(text) +
'&' +
Qs.stringify(props.query),
);
}

request.withCredentials = requestShouldUseWithCredentials();
setRequestHeaders(request, getRequestHeaders(props.requestUrl));

request.send();
if (props.isNewPlacesAPI) {
const { locationbias, locationBias, types, ...rest } = props.query;
request.send(
Qs.stringify({
rojiphil marked this conversation as resolved.
Show resolved Hide resolved
input: text,
sessionToken,
...rest,
}),
);
} else {
request.send();
}
} else {
_results = [];
setDataSource(buildRowsFromResults([]));
Expand Down Expand Up @@ -942,6 +1007,8 @@ GooglePlacesAutocomplete.propTypes = {
textInputHide: PropTypes.bool,
textInputProps: PropTypes.object,
timeout: PropTypes.number,
isNewPlacesAPI: PropTypes.bool,
fields: PropTypes.string,
};

GooglePlacesAutocomplete.defaultProps = {
Expand Down Expand Up @@ -986,6 +1053,8 @@ GooglePlacesAutocomplete.defaultProps = {
textInputHide: false,
textInputProps: {},
timeout: 20000,
isNewPlacesAPI: false,
fields: '*',
};

GooglePlacesAutocomplete.displayName = 'GooglePlacesAutocomplete';
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"dependencies": {
"lodash.debounce": "^4.0.8",
"prop-types": "^15.7.2",
"qs": "~6.9.1"
"qs": "~6.9.1",
"uuid": "^10.0.0"
},
"devDependencies": {
"@react-native-community/eslint-config": "2.0.0",
Expand Down