I need to calculate the distance between Longitude and Latitude in react native. I have the Longitude and Latitude of my current location and I have the Longitude and Latitude of my destination. Is their any easy way to calculate the distance?
I tried using geolib, but keep getting an error. Below is what I did:
npm i geolib
I put the geolib in my import statement too.
import {
AppRegistry,
StyleSheet,
FlatList,
Text,
View,
Alert,
TouchableOpacity,
Linking,
Image,
ScrollView,
RefreshControl,
Location,
geolib
} from 'react-native';
_renderItem = ({item, index}) => {
var dist = geolib.getDistance(
this.state.latitude,
this.state.longitude,
item.LatL,
item.Long2
);
return (
<View>
<Text>Latitude: {this.state.latitude}</Text>
<Text>Longitude: {this.state.longitude}</Text>
<Text>Latitude from file:{item.LatL}</Text>
<Text>Longitude from file :{item.Long2} </Text>
<Text style={styles.AddressSpace} >Miles:{dist }</Text>
</View>
);
Below is the error that I am getting:
TypeError: undefined is not an object
(evaluating '_reactNative.geolib.getDistance')
[![enter image description here][1]][1]
I am getting this error as soon as I put this code:
const dist = geolib.getDistance(
{ latitude, longitude },{ latitude: item.LatL, longitude: item.Long2 }
);
Not sure, but I am still getting the above error: Below is my entire code:
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.getDistance(
{ 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;
_ [1]: https://i.stack.imgur.com/8VadZ.png