react-native-location获取手机定位

962 阅读1分钟

title: react-native-location 获取手机定位
tags:

  • 定位
  • location

react-native-location 简介

  • 一个用于获取手机定位的 react native 第三方组件
  • 官方参考

安装

npm install --save react-native-location
or
yarn add react-native-location

链接库

  • android/settings.gradle
include ':react-native-location'
project(':react-native-location').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-location/android')

  • android/app/build.gradle
dependencies {
   ...
   implementation project(':react-native-location')
}

  • android/app/src/main/…/MainApplication.java 如果你的react native 版本比较高,这一步并不是必须的。
    On top, where imports are:
import com.github.reactnativecommunity.location.RNLocationPackage;

Add the RNLocationPackage class to your list of exported packages.

@Override
protected List<ReactPackage> getPackages() {
    return Arrays.asList(
            new MainReactPackage(),
            new RNLocationPackage()
    );
}

权限配置

  • 路径 android\app\src\main\AndroidManifest.xml
    Android manifest permissions
    You need to ensure that your AndroidManifest.xml contains this line:

If you want to access fine location then you should also include: ### Example ```js import React, {Component} from 'react'; import { Platform, PermissionsAndroid, View, Button, Text } from 'react-native'; import RNLocation from 'react-native-location';

RNLocation.configure({
distanceFilter: 5.0,
});

export default class TestGeo extends Component {
state={
longitude:’’,
latitude:’’,
timestamp:’’
}
// 获取权限
async componentDidMount() {
if (Platform.OS === ‘android’) {
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: ‘Contacts’,
message: ‘This app would like to view your contacts.’,
},
).then((res) => {
console.log(res);
});
} else {
console.log(1111111);
}
}

getPositions = () => {
RNLocation.subscribeToLocationUpdates((res) => {
console.log(res);
this.setState({longitude : res[0][‘longitude’]})
this.setState({latitude:res[0][‘latitude’]})
this.setState({timestamp : res[0][‘timestamp’]})
// “速度:” + location.coords.speed +
// “\n 经度:” + location.coords.longitude +
// “\n 纬度:” + location.coords.latitude +
// “\n 准确度:” + location.coords.accuracy +
// “\n 行进方向:” + location.coords.heading +
// “\n 海拔:” + location.coords.altitude +
// “\n 海拔准确度:” + location.coords.altitudeAccuracy +
// “\n 时间戳:” + location.timestamp;

});

};

render() {
return (

{this.state.longitude}
{this.state.latitude}
{this.state.timestamp}

);
}
}