0
votes

I have created my first React Native app using the latest Expo CLI using instructions from React Native docs:

npm install -g expo-cli
npm expo init AwesomeProject

Later I wanted to add the geolocation library to this app and it seems that the whole autolinking doesn't want to work for me. I have used the provided instructions:

yarn add @react-native-community/geolocation

And I haven't done the manual linking because I am using React Native in the currently newest version (above 0.59 as said in the readme of the library). After adding the sample code:

import Geolocation from '@react-native-community/geolocation';
Geolocation.getCurrentPosition(info => console.log(info));

I have started to get errors that the library should be linked. After manually invoking the link command it still unfortunately hasn't worked.

2

2 Answers

1
votes

I actually jumped out of these libraries and went full Expo on this (but i am still not sure if this is the right approach):

import { useState, useEffect } from "react";
import * as Permissions from "expo-permissions";
import * as Location from "expo-location";

export const useLocation = () => {
  const [location, setLocation] = useState();

  useEffect(() => {
    async function setLocationWithPerms() {
      const permissions = await Permissions.askAsync(Permissions.LOCATION);

      if (permissions.status === "granted") {
        const currentLocation = await Location.getCurrentPositionAsync({});
        setLocation(currentLocation);
      }
    }
    setLocationWithPerms();
  }, []);

  return location;
};
0
votes

Sometimes Geolocation.getcurrentPosition get some error..

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

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      latitude: 'lat',
      longitude: 'long',
    }
  }

  componentDidMount() {
    navigator.geolocation = require('@react-native-community/geolocation');
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        });
      },
      (error) => alert(error),
      { enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
    );
  }

  render(){
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        {this.state.latitude}
         </Text>
      <Text style={styles.paragraph}>
        {this.state.longitude}
         </Text>
    </View>
  );
}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

This is a simple demo example of geolocation. Try it out. And ask if any query.