【问题标题】:React Native - Get Location latitude and longitude using react-native-get-locationReact Native - 使用 react-native-get-location 获取位置纬度和经度
【发布时间】:2021-07-02 14:30:13
【问题描述】:

我正在创建一个使用手机位置的应用。我希望能够获取纬度和经度并将其用作 api 地址的一部分。

我一直在使用 react-native-get-location 跟踪此示例代码,并且能够以 json 格式打印信息,但无法提取纬度和经度并使用它们。

react-native-get-location

这是我的代码。

import GetLocation from 'react-native-get-location'

export default class App extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      isLoading: true,
      latitude: null,
      longitude: null,
      location: null
    };
  }

  _requestLocation = () => {
    GetLocation.getCurrentPosition({
      enableHighAccuracy: true,
      timeout: 150000,
    })
    .then(location => {
      this.setState ({
        location,
        isLoading: false,
      });
    })
    .catch(error => {
      const { code, message} = error;
      if (code === 'CANCELLED') {
        Alert.alert('location cancelled by user or by another request');
      }
      if (code === 'UNAVAILABLE') {
        Alert.alert('Location service is disabled or unavailable');
      }
      if (code === 'TIMEOUT') {
        Alert.alert('Location request timed out');
      }
      if (code === 'UNAUTHORIZED') {
        Alert.alert('Authorization denied')
      }
      this.setState({
        location: null,
        isLoading: false,
      });
    });
  }


componentDidMount() {
GetLocation.getCurrentPosition(async (info) => {
  const location = await GetLocation(
    info.coords.latitude,
    info.coords.longitude
  );
})
const fetch = require('node-fetch');
 fetch('https://api.weatherapi.com/v1/forecast.json?&q=London', {
   method: 'GET',
   headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'

   },
 }).then((response) => response.json())
   .then((responseJson) => {
   console.log(responseJson);
     this.setState({
       isLoading: false, 
       dataSource: responseJson,  
     })       
   }).catch((error) => {
     console.error(error);
   });
}

  render() {
    const {location, isLoading} = this.state;
    if (this.state.isLoading) {
  return (
    <View style={{flex: 1, paddingTop: 20}}>
     <ActivityIndicator /> 
  
  </View>
  );
    }

    return (
     <View style={{flex:1, paddingTop: 20}}>
<Text>{JSON.stringify(location, 0, 2)}</Text>

<View style={{flex:1, flexDirection: 'row', textAlign: 'center', paddingLeft: 90}}>

<Button
                        disabled={isLoading}
                        title="Get Location"
                        onPress={this._requestLocation}
                    />
</View>

      </View>
       )
      }
   }

【问题讨论】:

    标签: react-native gps


    【解决方案1】:

    使用expo-location 而不是react-native-get-location,因为它很容易实现。

    这是工作应用程序: Expo Snack

    截图:

    import React, { useEffect, useState } from 'react';
    import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
    import Constants from 'expo-constants';
    
    // You can import from local files
    
    let apiKey = 'YOUR_API_KEY';
    
    import * as Location from 'expo-location';
    
    export default function App() {
      const [location, setLocation] = useState(null);
      const [errorMsg, setErrorMsg] = useState(null);
      const [address, setAddress] = useState(null);
      // const [getLocation, setGetLocation] = useState(false);
    
      const getLocation = () => {
        (async () => {
          let { status } = await Location.requestPermissionsAsync();
          if (status !== 'granted') {
            setErrorMsg('Permission to access location was denied');
          }
    
          Location.setGoogleApiKey(apiKey);
    
          console.log(status);
    
          let { coords } = await Location.getCurrentPositionAsync();
    
          setLocation(coords);
    
          console.log(coords);
    
          if (coords) {
            let { longitude, latitude } = coords;
    
            let regionName = await Location.reverseGeocodeAsync({
              longitude,
              latitude,
            });
            setAddress(regionName[0]);
            console.log(regionName, 'nothing');
          }
    
          // console.log();
        })();
      };
    
      return (
        <View style={styles.container}>
          <Text style={styles.big}>
            {!location
              ? 'Waiting'
              : `Lat: ${location.latitude} \nLong: ${
                  location.longitude
                } \n${JSON.stringify(address?.['subregion'])}`}
          </Text>
          <TouchableOpacity onPress={getLocation}>
            <View
              style={{
                height: 100,
                backgroundColor: 'teal',
                justifyContent: 'center',
                alignItems: 'center',
                borderRadius: 10,
                marginTop: 20,
              }}>
              <Text style={styles.btnText}> GET LOCATION </Text>
            </View>
          </TouchableOpacity>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: 'white',
        alignItems: 'center',
        justifyContent: 'center',
      },
      big: {
        fontSize: 18,
        color: 'black',
        fontWeight: 'bold',
      },
      btnText: {
        fontWeight: 'bold',
        fontSize: 25,
        color: 'white',
      },
    });
    

    【讨论】:

      【解决方案2】:

      react-native-geolocation-service 也是获取纬度和经度值的好选择。

      示例用法:

      import GeoLocation from 'react-native-geolocation-service';
      
      const getDeviceCurrentLocation = async () => {
        return new Promise((resolve, reject) =>
          GeoLocation.getCurrentPosition(
            (position) => {
              resolve(position);
            },
            (error) => {
              reject(error);
            },
            {
              enableHighAccuracy: true, // Whether to use high accuracy mode or not
              timeout: 15000, // Request timeout
              maximumAge: 10000 // How long previous location will be cached
            }
          )
        );
      };
      

      【讨论】:

      • 怎么得到经纬度,没有这个教程/例子
      • 读取github.com/Agontuk/react-native-geolocation-service/#usage 成功时返回一个包含纬度和经度的对象。即从上面相同的代码,const { latitude, longitude } = getDeviceCurrentLocation();
      • 谢谢你发送这个,我去看看
      • 甚至无法通过它来询问位置,我已按照说明进行操作
      猜你喜欢
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多