Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Undefined is not an object - Geolocation

Tags:

react-native

I am using Windows 10 and am running an Android 7.0 device.

I am trying to make the device display the lat and long of it's current position using geolocation - when the user pressed a button.

I created a button and made an alert message appear when the user clicked it - so far so good.

Then I tried adding the get current position and then my app crashes with the error:

undefined is not an object (evaluating '_reactNative.Geolocation.getCurrentPosition')

Here is my code:

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Button,
  Alert,
  Geolocation
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>

        <Button
          onPress={() => {
            var loc = Geolocation.getCurrentPosition(geo_success, [geo_error], [geo_options]);
            Alert.alert(loc);

            //Alert.alert('You tapped the button!');
          }}
          title="Display GPS"
        />
      </View>
    );
  }
}

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

What does "undefined is not an object" mean, and how do I solve it? (I got the same error earlier, when I tried to access the camera.)

like image 568
Phrosen Avatar asked Apr 13 '18 10:04

Phrosen


1 Answers

Update: The feature has been removed from react-native core, so the below answer is no longer invalid.

The React-Native (v 0.55) Geolocation docs say,

As a browser polyfill, this API is available through the navigator.geolocation global - you do not need to import it.

Don't import Geolocation from react-native. Instead use navigator.geolocation directly which is a global object.

For example,

navigator.geolocation.getCurrentPosition(
  (position) => console.log(position),
  (err) => console.log(err),
  { enableHighAccuracy: false, timeout: 8000, maximumAge: 10000 }
);
like image 97
Ravi Raj Avatar answered Oct 10 '22 21:10

Ravi Raj