react-native-amap-geolocation icon indicating copy to clipboard operation
react-native-amap-geolocation copied to clipboard

您好,有个需求, 获取位置函数的封装,

Open phpsmarter opened this issue 5 years ago • 3 comments

为了节省大家的时间,请尽可能详细地说明问题,并最好提供截图(特别是出错信息)。 我试过了想把初始化部分封装一个函数, 直接返回一个坐标, 但是 不知道return 在哪里写

phpsmarter avatar May 25 '19 03:05 phpsmarter

想把初始化部分封装一个函数, 直接返回一个坐标

不太确定你要做什么,感觉上是你对 js 的异步返回不够了解?首先先确定你已经知道 promise await sync

qiuxiang avatar May 25 '19 04:05 qiuxiang

想把初始化部分封装一个函数, 直接返回一个坐标

不太确定你要做什么,感觉上是你对 js 的异步返回不够了解?首先先确定你已经知道 promise await sync

现在React 中有 Hooks方法 例如 useLocation , 想达到的目标就是在想获取位置的地方直接使用一个函数获取地理信息

import { PermissionsAndroid } from "react-native";
import { init, Geolocation } from "react-native-amap-geolocation";

await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION);

await init({
  ios: "9bd6c82e77583020a73ef1af59d0c759",
  android: "043b24fe18785f33c491705ffe5b6935"
});

Geolocation.getCurrentPosition(({ coords }) => {
  console.log(coords);   // 就是这里,想把coords直接返回,
});

用一个函数封装上面的代码, 直接获取返回的coords.

现在退而求其次的方式是 在这个地方 可以用redux 来存, 可以用本地存储, 也可以用useConext来存.

如果想封装成useLocation的类似的方法, 就只需要返回coords,但是写了几个返回都是undefined, 所以不知道在哪里写return,

phpsmarter avatar May 25 '19 07:05 phpsmarter

想把初始化部分封装一个函数, 直接返回一个坐标

不太确定你要做什么,感觉上是你对 js 的异步返回不够了解?首先先确定你已经知道 promise await sync

初步已经封装好了.参考的是这篇文章 https://www.hooks.guide/react-use/useGeolocation

也可以使用useContextState hooks函数在 app的入口获取信息,然后在实际应用中通过Provider来消费数据, 如果数据管理不太复杂的话, 就不用redux了.

import React, { useEffect, useState } from "react";
import {
  View,
  StyleSheet,
  Text,
  Linking,
  Platform,
  PermissionsAndroid
} from "react-native";
import {
  init,
  Geolocation,
  setNeedAddress
} from "react-native-amap-geolocation";

const useAmapLocation = async () => {
  const [state, setState] = useState({
    accuracy: null,
    altitude: null,
    altitudeAccuracy: null,
    heading: null,
    latitude: null,
    longitude: null,
    speed: null
  });
  let mounted = true;
  let watchId;

useEffect(() => {
    PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION
    );

    init({
      ios: "",
      android: "9eb25e7e634ffe0810e1bd08bcdaee81"
    });
    setNeedAddress(true);
    //watchId = navigator.geolocation.watchPosition(onEvent);

    Geolocation.getCurrentPosition(({ coords }) => {
      console.log(coords);
      setState({
        accuracy: coords.accuracy,
        altitude: coords.altitude,
        altitudeAccuracy: coords.altitudeAccuracy,
        heading: coords.heading,
        latitude: coords.latitude,
        longitude: coords.longitude,
        speed: coords.speed
      });
    });
  }, [0]);

  return state;
};

//使用useAmapLocation()的位置
const Location = () => {
  useAmapLocation().then(data => console.log(data));

  return (
    <View>
      <Text>location</Text>
    </View>
  );
};



phpsmarter avatar May 25 '19 10:05 phpsmarter