1.高德地图官网申请一个web平台key,和android平台key
2.安装依赖
yarn add react-native-amap-geolocation
npx react-native link react-native-amap-geolocation
yarn add @react-native-community/geolocation
3.项目app>src>app>AndroidManifest.xml 加入权限配置
4.封装
import React from 'react';
import {PermissionsAndroid, Platform} from 'react-native';
import {init} from 'react-native-amap-geolocation';
import geolocation from '@react-native-community/geolocation';
import axios from 'axios';
const useGeo = () => {
const initGeo = async () => {
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
await init({
android: '***************',//android平台key
// ios: '################',
});
return Promise.resolve();
}
}
};
const GetCurrentPosition = async () => {
return new Promise((resolve, reject) => {
geolocation.getCurrentPosition(({coords}) => {
console.log('coords', coords);
resolve(coords);
}, reject);
});
};
const getCityByLocation = async () => {
const {longitude, latitude} = await GetCurrentPosition();
const res = await axios.get('https://restapi.amap.com/v3/geocode/regeo', {
// key 高德地图中第一个应用的key
params: {
location: `${longitude},${latitude}`,
key: '***************',//web平台key
},
});
return Promise.resolve(res);
};
return {initGeo, GetCurrentPosition, getCityByLocation};
5.先在App.js初始化
/* eslint-disable react-native/no-inline-styles */
import React, {useState, useEffect} from 'react';
import Store from './src/redux/store';
import {View} from 'react-native';
import Nav from './src/router';
import {Provider} from 'react-redux';
import {NativeBaseProvider} from 'native-base';
import Geo from './src/utils/Geo';
import UseWrap from './src/wrap';
const App = () => {
const [isInitGeo, setIsInitGeo] = useState(false);
useEffect(() => {
async function getLocation() {
await Geo.initGeo();
setIsInitGeo(true);
}
getLocation();
}, []);
return (
<NativeBaseProvider>
<View style={{flex: 1}}>
<Provider store={Store}>
<UseWrap>{isInitGeo ? <Nav /> : null}</UseWrap>
</Provider>
</View>
</NativeBaseProvider>
);
};
export default App;
6.调用获取地理位置
import Geo from '../../utils/Geo';
useEffect(() => {
async function getLocation() {
Toast.show({title: '获取地理位置'});
const res = await Geo.getCityByLocation();
console.log('res', res);
const address1 = res.regeocode.formatted_address;
const city1 = res.regeocode.addressComponent.district;
const lng1 =
res.regeocode.addressComponent.streetNumber.location.split(',')[0];
const lat1 =
res.regeocode.addressComponent.streetNumber.location.split(',')[1];
setCity(city1);
setAddress(address1);
setLat(lat1);
setLng(lng1);
}
getLocation();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);