在React Native中使用geolib时出现错误

时间:2019-05-02 00:12:19

标签: reactjs react-native

过去几个小时,我一直在努力解决这个问题。我正在使用Geolib计算两个点之间的距离,但是却不断出现错误。下面是我的代码。

import React, { Component } from 'react';
import { View, Text, item } from 'react-native';
import geolib from 'geolib';
class ServiceListDetails 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() {
    const { latitude, longitude } = this.state;

    const dist = geolib.getDistanceSimple(
  { latitude, longitude },
  { latitude: 33.935558, longitude: -117.284912 }
);
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        <Text>Miles:{dist} </Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

export default ServiceListDetails;

当我添加此特定行时,我得到错误:

   const dist = geolib.getDistanceSimple(
      { latitude, longitude },
      { latitude: 33.935558, longitude: -117.284912 }
    );

我按如下所示安装了geolib:

npm i geolib

并收到以下消息:

npm WARN eslint-plugin-react-native@3.2.1 requires a peer of eslint@^3.17.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ geolib@2.0.24
updated 1 package in 10.167s

以下是错误消息的屏幕截图:

enter image description here

添加以下代码行时出现错误:

1 个答案:

答案 0 :(得分:0)

您必须向该应用授予位置访问权限。 首先,将此代码添加到AndroidManifest.xml(android> app> src> main> AndroidManifest.xml)

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

现在看起来应该是

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.packagename">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
      ...some content...
    </application>

</manifest>

然后执行gradle clean。 (希望您知道该怎么做)。之后,重新启动服务器(react-native run-android / ios)