【问题标题】:How to get the city location in react-native?如何在 react-native 中获取城市位置?
【发布时间】:2021-02-21 23:09:15
【问题描述】:
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';

import * as Location from 'expo-location'
import Permissions from "expo-permissions";

export default function App() {
  const [address, setAddress] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

  useEffect(() => {
    console.log(errorMsg)
    console.log(address)
  }, []);

  const _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== "granted") {
      setErrorMsg = "Permission to access location was denied";
    }
    const location = await Location.reverseGeocodeAsync({});
    const address = await Location.reverseGeocodeAsync(location.coords);
    address;

    _getLocationAsync();
  };

  let text = "Waiting...";
  if (errorMsg) {
    text = setErrorMsg;
  } else if (address) {
    text = setAddress[0].city;
  }

  return (
    <View style={styles.container}>
      <Text style={styles.text}>{text}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#bcbcbc',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 20
  }
});

我有这段代码可以在 react-native 中获取城市位置,但我不知道我还应该做什么来获取位置。我尝试了一段时间,但我改变了很多东西,不知道我到底做了什么...... 如果有人可以在这里帮助我,我将不胜感激

【问题讨论】:

    标签: react-native geolocation location use-effect city


    【解决方案1】:

    我使用了来自 '@react-native-comunity/geolocation' 的 Geolocation,它返回纬度和经度。

    Geolocation.getCurrentPosition(async (info) => {
         const location = await getLocation(
         info.coords.latitude,
         info.coords.longitude,
         );
         ...
    

    并使用 google maps api 进行地理编码

    export const getLocation = async (lat: number, long: number) => {
      const apiKey = 'my api key'
      return Api.get(
        `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${apiKey}`,
      );
    };
    

    希望这对你有用

    【讨论】:

      猜你喜欢
      • 2023-02-05
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多