在手机设置中未启用位置权限时,应用崩溃

时间:2019-07-01 04:26:52

标签: react-native react-native-maps

我在从用户获取当前位置的本地应用程序中做出了反应。为此,我必须从手机的设置中启用位置权限,否则尽管我在AndroidManifest.xml中启用了权限,该应用程序也会崩溃。应用程序甚至不要求使用该位置的权限。但是它在模拟器中效果很好。这是我试图获取用户位置的组件。

class LocationTrack extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude1: null,
      longitude1: null,
      error:null,
      latitude: 37.78825,
      longitude: -122.4324,
      routeCoordinates: [],
      distanceTravelled: 0,
      prevLatLng: {},
      coordinate: new AnimatedRegion({
        latitude: 37.78825,
        longitude: -122.4324,
        latitudeDelta: 0,
        longitudeDelta: 0
      })
    };
    this.reftrack = firebase.firestore().collection('jobTracking');
  }

   componentDidMount() {
    const { coordinate } = this.state;
    this.watchID = navigator.geolocation.watchPosition(
      position => {
        const { routeCoordinates, distanceTravelled } = this.state;
        const { latitude, longitude, accuracy, altitude, heading, speed } = position.coords;

        const newCoordinate = {
          latitude,
          longitude,
          accuracy,
          altitude,
          heading,
          speed
        };
        console.log({ newCoordinate });

        this.reftrack.add({
          newCoordinate: newCoordinate,
          distance : distanceTravelled + this.calcDistance(newCoordinate)
        }).then(function () {
          console.log("new location set");

        }).catch(function (error) {
          console.error("Error setting document: ", error);
        });

        if (Platform.OS === "android") {
          if (this.marker) {
            this.marker._component.animateMarkerToCoordinate(
              newCoordinate,
              500
            );
          }
        } else {
          coordinate.timing(newCoordinate).start();
        }

        this.setState({
          latitude,
          longitude,
          routeCoordinates: routeCoordinates.concat([newCoordinate]),
          distanceTravelled:
            distanceTravelled + this.calcDistance(newCoordinate),
          prevLatLng: newCoordinate
        });

      },
      error => console.log(error),
      {
        enableHighAccuracy: true,
        timeout: 20000,
        maximumAge: 1000,
        distanceFilter: 10
      }
    );
  }
  async componentWillMount() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          'title': 'Example App',
          'message': 'Example App access to your location '
        }
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the location")
        alert("You can use the location");
      } else {
        console.log("location permission denied")
        alert("Location permission denied");
      }
    } catch (err) {
      console.warn(err)
    }
  }
  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);

  }

  getMapRegion = () => ({
    latitude: this.state.latitude,
    longitude: this.state.longitude,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA
  });

  calcDistance = newLatLng => {
    const { prevLatLng } = this.state;
    return haversine(prevLatLng, newLatLng) || 0;
  };

  
  render() {
    return (
      <View style={styles.container}>
        <MapView
          style={styles.map}
          provider={PROVIDER_GOOGLE}
          showUserLocation
          followUserLocation
          loadingEnabled
          region={this.getMapRegion()}
        >
          <Polyline coordinates={this.state.routeCoordinates} strokeWidth={5} />
          <Marker.Animated
            ref={marker => {
              this.marker = marker;
            }}
            coordinate={this.state.coordinate}
          />
        </MapView>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={[styles.bubble, styles.button]}>
            <Text style={styles.bottomBarContent}>
              {parseFloat(this.state.distanceTravelled).toFixed(2)} km
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}


export default LocationTrack;

0 个答案:

没有答案