0

我有两个问题。一个是如果我使用命令 react native run-android 启动应用程序,我可以看到我当前位置的经度和纬度。如果我重新加载屏幕,我会收到一个超时错误,提示“位置请求超时”并且我看不到经度和纬度。下面是图片

在此处输入图像描述

我遇到的另一个问题是,当我尝试计算经度和纬度两个坐标之间的距离时,我得到路径错误。以下是我的代码和错误的屏幕截图:

import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Linking } from 'react-native';
import geolib from "geolib";

class GeolocationExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null,
    };
  }



  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );
  }

  render() {

    let geolib = require('geo-lib');


    let result =geolib.Distance({
     p1: { lat: this.state.latitude, lon: this.state.longitude },
     p2: { lat: 33.613355, lon: -117.373261 }
 });


    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        <Text>Distance between two points:result </Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}


      </View>
    );
  }
}

export default GeolocationExample;

在此处输入图像描述

我不确定为什么会出现这个错误。

任何帮助将不胜感激。

4

2 回答 2

1

试试这个有效的更新代码!

import {getDistance} from 'geolib';
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";

export default class Locations extends Component
{
    state = {  
        destinationLat: 31.6200,
        destinationLong: 74.8765,
        distance:null,
        startLat:52.528308,
        startLong:1.3817765
    };
    async componentDidMount(){
        let location = await Location.getCurrentPositionAsync({
            enableHighAccuracy: true,
        });
        this.setState({
            startLat: location.coords.latitude,
            startLong: location.coords.longitude,
          });
        var dis = getDistance(
            {latitude: location.coords.latitude, longitude: location.coords.longitude},
            {latitude: this.state.destinationLat, longitude: this.state.destinationLong},
          );
          this.setState({
            distance: dis/1000,
          });
    };
    render(){
        return(
            <Text>{this.state.distance} KMs</Text>
        );
    }
}
于 2020-11-11T19:44:49.697 回答
0

某些 Android API 的位置超时错误是臭名昭著的。该软件包旨在解决此问题。

对于您的路径问题,您是从顶部没有破折号的“geolib”导入的,但是在渲染方法中需要带有破折号的“geo-lib”。我会检查以确保您安装了哪个并删除对另一个的引用。

于 2018-05-03T20:35:32.217 回答