Faiz Lotfy
Faiz Lotfy

Reputation: 121

get user city and country in react native

I am new to react native (and app developing) and I want to show a message to the user when he uses the app for the first time that tells the user that the app thinks he is in city CITY, in country COUNTRY.

I could not find a working example that I can use. Most of what I found are APIs that give the longitude and latitudes of the user, and some other APIs that decode (lon., lat.) into city and country. Both were not well documented with a valid working example

How may I achieve this goal? Is/are there methods or plugin(s) that I can use?

Here is a piece of code (I tried many examples) I tried:

import { PermissionsAndroid, Platform } from 'react-native'

    const requestPermission = () => {
    if(Platform.OS === 'ios') return Promise.resolve(true)
    return PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        'title': 'Allow to get coordinates',
        'message': 'This app requires GPS coordinates in order to proceed '
      }
    ).then(granted => {
        if(granted === PermissionsAndroid.RESULTS.GRANTED) {
          return Promise.resolve("You can use the location")
        } else {
          return Promise.reject("Location permission denied")
        }
    })
    }

    const getCoordinates = () => {
    return requestPermission().then(ok => {
        return new Promise((resolve, reject) => {
            const options = Platform.OS === 'android' ? 
{enableHighAccuracy:true,timeout:5000}
                                        : 
{enableHighAccuracy:true,timeout:5000,maximumAge:2000};
            global.navigator.geolocation.getCurrentPosition(resolve, reject, options)
      })
    })
    }

    export default getCoordinates

The error I get is this:

Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}) If you meant to render a collection of children, use an array instead.

Upvotes: 0

Views: 6177

Answers (1)

Tuan Nguyen
Tuan Nguyen

Reputation: 2607

  1. Get current Location (require location permission granted) (remove myLocationCallback)

enter image description here

  1. Pass location(latitude, longitude) to Google Map API (you need google api key) enter image description here

Upvotes: 2

Related Questions