React Native 高德地图定位 hooks

安装

yarn add react-native-amap-geolocation

使用

  const {coords} = useLocation()
  console.log('ccc', coords) // 当前位置,非实时
 
  const {location} = useLocation('watch')
  console.log('l333', location.city) // 实时定位

useLocation.ts

import React, {useCallback, useEffect, useState} from "react"
import { PermissionsAndroid } from "react-native"
import { init, Geolocation } from "react-native-amap-geolocation"
import {AMAP_ANDROID_KEY} from '@/constants/constants'



interface Position {
  coords: {
    /** 精度 米 */
    accuracy: number
    altitude?: number
    heading: number
    latitude: number
    longitude: number
    speed: number
  }
  location?: any
}
interface PositionWatch {
  coords: {
    /** 精度 米 */
    accuracy: number
    altitude?: number
    heading: number
    latitude: number
    longitude: number
    speed: number
  }
  location: {
    accuracy: number
    adCode: string 
    address: string               //  "重庆市九龙坡区科城支路85号靠近重庆市九龙坡区人力资源和社会保障综合服务中心", 
    altitude: number
    city: string                  //  "重庆市", 
    cityCode: string              //  "023", 
    coordinateType: string        //  "GCJ02", 
    country: string               //  "中国", 
    description: string           //  "在重庆市九龙坡区人力资源和社会保障综合服务中心附近", 
    district: string              //  "九龙坡区", 
    errorCode: number             //  0,
    errorInfo: string             //  "success", 
    gpsAccuracy: number           //  -1,
    heading: number               //   0, 
    latitude: number              //   29.512879, 
    locationType: number          //   2, 
    longitude: number             //  106.458555,
    poiName: string               //  "重庆市九龙坡区人力资源和社会保障综合服务中心", 
    province: string              //  "重庆市", 
    speed: number                 //  0, 
    street: string                //  "科城支路", 
    streetNumber: string          //  "85号", 
    timestamp: number             //  1651214072119, 
    trustedLevel: number          // 1
  }
  timestamp: number 
}
type TLocType = 'watch'
function useLocation (): Position
function useLocation (locType: TLocType): PositionWatch
function useLocation (locType?: TLocType): Position | PositionWatch {
  const [position, setPosition] = useState({
    coords: {
      latitude: 0,
      longitude: 0,
      accuracy: 0,
      heading: 0,
      speed: 0,
    },
    location: {}
  })

  /** 初始化 */
  const initAMap = useCallback(async () => {
    await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
    ]);
    
    await init({
      ios: '',
      android: AMAP_ANDROID_KEY
    })
  }, [])

  /** 获取当前位置 */
  const getPosition = useCallback<() => Promise>(() => {
    return new Promise((resolve, reject) => {
      Geolocation.getCurrentPosition(({ coords }) => {
        resolve({coords: coords})
      }, err => {
        reject(err)
      })
    })
  }, [])


  useEffect(() => {
    let wid
    async function init() {
      await initAMap()
      if(locType === 'watch'){
        wid = Geolocation.watchPosition((curPosition) => {
          setPosition({...curPosition})
        }, (err) => {
          console.log('实时定位出错:', err)
          Geolocation.clearWatch(wid)
        })
      }else{
        const curPos = await getPosition()
        setPosition({...curPos, location: {}})
      }
    }
    init()

    return () => {
      locType === 'watch' && Geolocation.clearWatch(wid)
    }
  }, [initAMap, getPosition, locType])

  return position
}

export default useLocation

你可能感兴趣的:(react-native)