5

I'm trying to get a user's location coordinates in React Native from their iPhone, but when I follow Facebook's Geolocation setup, it isn't returning a response with that user's data (https://facebook.github.io/react-native/docs/geolocation.html#content). I'm not sure if there's an issue with the code (my GeoLocation component's code is below). I'm also testing through the iOS simulator - so not sure if pulling geolocation only works through an actual device or if the simulator can use your location based on wifi.

If this the correct way to find user location or is there a better way in react native?

Thanks - any and all help is greatly appreciated!

const React = require('react-native');

const {
  StyleSheet,
  Text,
  View,
} = React;

exports.framework = 'React';
exports.title = 'Geolocation';
exports.description = 'Examples of using the Geolocation API.';

exports.examples = [
  {
    title: 'navigator.geolocation',
    render: function(): ReactElement {
      return <GeolocationExample />;
    },
  }
];

const GeolocationExample = React.createClass({
  watchID: (null: ?number),

  getInitialState: function() {
    return {
      initialPosition: 'Can\'t find',
      lastPosition: 'Can\'t find',
    };
  },

  componentDidMount: function() {
    navigator.geolocation.getCurrentPosition(
      (initialPosition) => this.setState({initialPosition}),
      (error) => alert(error.message),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
    this.watchID = navigator.geolocation.watchPosition((lastPosition) => {
      this.setState({lastPosition});
    });
  },

  componentWillUnmount: function() {
    navigator.geolocation.clearWatch(this.watchID);
  },

  render: function() {
    return (
      <View>
        <Text>
          <Text style={styles.title}>Initial position: </Text>
          {JSON.stringify(this.state.initialPosition)}
        </Text>
        <Text>
          <Text style={styles.title}>Current position: </Text>
          {JSON.stringify(this.state.lastPosition)}
        </Text>
      </View>
    );
  }
});

const styles = StyleSheet.create({
  title: {
    fontWeight: '500',
  },
});

module.exports = GeolocationExample;
dace
  • 5,819
  • 13
  • 44
  • 74

2 Answers2

5

You need to set the location in the Simulator. There is an option for that in simulator menus as described in this question: Set the location in iPhone Simulator

Community
  • 1
  • 1
Jarek Potiuk
  • 19,317
  • 2
  • 60
  • 61
1

Don't forget to include the NSLocationWhenInUseUsageDescription key in Info.plist per the instructions for iOS

Kyle Kwon
  • 361
  • 2
  • 5