FaridSafi / react-native-google-places-autocomplete

Customizable Google Places autocomplete component for iOS and Android React-Native apps
MIT License
1.99k stars 849 forks source link

Global navigator object not found with Typescript #876

Open irelandjj opened 1 year ago

irelandjj commented 1 year ago

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

If you are using expo please indicate here:

Add any other context about the problem here, screenshots etc

orwashams commented 1 year ago

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.

mohameddjebloun commented 1 year ago

I fixed the readonly error like this (navigator.geolocation as any) = require('@react-native-community/geolocation');