react-native-google-places-autocomplete
react-native-google-places-autocomplete copied to clipboard
Global navigator object not found with Typescript
Describe the problem
I want to get the current location in the autocomplete dropdown and I am using react-native-geolocation-service' for this as suggested in the documentation. As suggested I add the line navigator.geolocation = require('react-native-geolocation-service'); in my code but the navigator object is not being found as I would expect as I am using Typescript. What modifications do I need to do to fix this?
Reproduction - (required - issue will be closed without this)
Steps to reproduce the behaviour - a minimal reproducible code example, link to a snack or a repository. I use the example code to get the current location in the autocomplete component (as seen here: https://github.com/FaridSafi/react-native-google-places-autocomplete#more-examples) in a .tsx file using react-native-geolocation-service. The navigator object can't be found.
import React from 'react';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
navigator.geolocation = require('react-native-geolocation-service');
const GooglePlacesInput = () => {
return (
<GooglePlacesAutocomplete
placeholder='Search'
onPress={(data, details = null) => {
// 'details' is provided when fetchDetails = true
console.log(data, details);
}}
query={{
key: 'YOUR API KEY',
language: 'en',
}}
currentLocation={true}
currentLocationLabel='Current location'
/>
);
};
export default GooglePlacesInput;
Additional context
- Library Version: ^2.5.1
- React Native Version: 0.71.3 -"react-native-geolocation-service": "^5.3.1"
If you are using expo please indicate here:
- I am not using expo
Add any other context about the problem here, screenshots etc
in tsconfig.json you can add the "DOM" library to be included in the compilation:
"compilerOptions": {
....
"lib":[
...
"DOM",
...
]
...
}
Although it does give you objects like "window", "document" and "navigator" and their correct type, the geolocation property is readonly, so you'll still get an error. I havn't figured how to get around that, im open for any suggestions.
I fixed the readonly error like this
(navigator.geolocation as any) = require('@react-native-community/geolocation');