Geolocation #

The Geolocation API extends the web spec:

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

iOS #

You need to include the NSLocationWhenInUseUsageDescription key in Info.plist to enable geolocation. Geolocation is enabled by default when you create a project with react-native init.

Android #

To request access to location, you need to add the following line to your app's AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Android API >= 18 Positions will also contain a mocked boolean to indicate if position was created from a mock provider.

Methods #

static getCurrentPosition(geo_success, geo_error?, geo_options?) #

Invokes the success callback once with the latest location info. Supported options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool) On Android, this can return almost immediately if the location is cached or request an update, which might take a while.

static watchPosition(success, error?, options?) #

Invokes the success callback whenever the location changes. Supported options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool), distanceFilter(m)

static clearWatch(watchID) #

static stopObserving(0) #

Вы можете отредактировать перевод на GitHub и создать pull request!

Examples #

Редактировать на GitHub
/* eslint no-console: 0 */ 'use strict'; var React = require('react'); var ReactNative = require('react-native'); var { StyleSheet, Text, View, } = ReactNative; exports.framework = 'React'; exports.title = 'Geolocation'; exports.description = 'Examples of using the Geolocation API.'; exports.examples = [ { title: 'navigator.geolocation', render: function(): ReactElement<any> { return <GeolocationExample />; }, } ]; class GeolocationExample extends React.Component { state = { initialPosition: 'unknown', lastPosition: 'unknown', }; watchID: ?number = null; componentDidMount() { navigator.geolocation.getCurrentPosition( (position) => { var initialPosition = JSON.stringify(position); this.setState({initialPosition}); }, (error) => alert(JSON.stringify(error)), {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} ); this.watchID = navigator.geolocation.watchPosition((position) => { var lastPosition = JSON.stringify(position); this.setState({lastPosition}); }); } componentWillUnmount() { navigator.geolocation.clearWatch(this.watchID); } render() { return ( <View> <Text> <Text style={styles.title}>Initial position: </Text> {this.state.initialPosition} </Text> <Text> <Text style={styles.title}>Current position: </Text> {this.state.lastPosition} </Text> </View> ); } } var styles = StyleSheet.create({ title: { fontWeight: '500', }, });