React-Native Geolocation获取地理位置

1:iOS xcode工程启用定位

Info.plist中增加NSLocationWhenInUseUsageDescription字段来启用定位功能

2:android

需要在AndroidManifest.xml文件中加入如下一行:

3:Geolocation的方法

//获取当前地理位置
navigator.geolocation.getCurrentPosition(geo_success: Function, geo_error?: Function, geo_options?: GeoOptions)

//监听地理位置变化
watchID  = navigator.geolocation.watchPosition(success: Function, error?: Function, options?: GeoOptions)

//清理监听
navigator.geolocation.clearWatch(watchID);

//停止监听
navigator.geolocation.stopObserving()

4:代码调用

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

class RNGeolocationView extends Component {

    _watchID;

    constructor(props) {
        super(props);
        this.state = {
            text1: '',
            text2: ''
        }
    }

    componentDidMount() {
        navigator.geolocation.getCurrentPosition(
            (position) => {
                let initialPosition = JSON.stringify(position);
                this.setState({
                    text1: initialPosition
                });
            },
            (error) => alert(error.message),
            {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
        );

        this._watchID = navigator.geolocation.watchPosition((position)=> {
            let lastPosition = JSON.stringify(position);
            this.setState({
                text2: lastPosition
            });
        }, (error)=> {
            alert(error.message)
        })
    }

    componentWillUnmount() {
        navigator.geolocation.clearWatch(this._watchID);
    }

    render() {
        return (
            
                {this.state.text1}

                {this.state.text2}
            
        )
    }
}
AppRegistry.registerComponent('RNGeolocationView', ()=>RNGeolocationView);

你可能感兴趣的:(React-Native Geolocation获取地理位置)