Reputation: 2698
I have two issues. One is I can see the Longitude and Latitude of my current location if I start the application using command react native run-android. If I reload the screen, I get a timeout error saying "Location Request timed out" and I don't see Longitude and Latitude. Below is the image
Another issue I am having is when I tried to calculate the distance between two coordinates of Longitude and Latitude then I get path error. Below is my code and the screen shot of the error:
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;
I am not sure why this error is coming up.
Any help will be greatly appreciated.
Upvotes: 0
Views: 4345
Reputation: 809
Try out this working updated code!
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>
);
}
}
Upvotes: 1
Reputation: 581
The location timeout error is notorious for certain Android APIs. This package is meant to address this problem.
For your path problem, you're importing from 'geolib' with no dash at the top, but then are requiring 'geo-lib' with a dash within your render method. I would check to make sure which one you have installed and remove references to the other.
Upvotes: 0