react-nativegeolocationlocationuse-effectcity

How to get the city location in react-native?


import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';

import * as Location from 'expo-location'
import Permissions from "expo-permissions";

export default function App() {
  const [address, setAddress] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

  useEffect(() => {
    console.log(errorMsg)
    console.log(address)
  }, []);

  const _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== "granted") {
      setErrorMsg = "Permission to access location was denied";
    }
    const location = await Location.reverseGeocodeAsync({});
    const address = await Location.reverseGeocodeAsync(location.coords);
    address;

    _getLocationAsync();
  };

  let text = "Waiting...";
  if (errorMsg) {
    text = setErrorMsg;
  } else if (address) {
    text = setAddress[0].city;
  }

  return (
    <View style={styles.container}>
      <Text style={styles.text}>{text}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#bcbcbc',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 20
  }
});

I have this code to get the city location in react-native, but I don't know what else I should do to get the location. I'm trying this for a while but I'm changing so many things and don't know exactly what I did... I'd appreciate if someone could help me a little here


Solution

  • I used Geolocation from '@react-native-comunity/geolocation' which returns latitude and longitude.

    Geolocation.getCurrentPosition(async (info) => {
         const location = await getLocation(
         info.coords.latitude,
         info.coords.longitude,
         );
         ...
    

    And used google maps api for geocoding

    export const getLocation = async (lat: number, long: number) => {
      const apiKey = 'my api key'
      return Api.get(
        `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${apiKey}`,
      );
    };
    

    Hope this works for you