'Calculate distance between two lat+lng coordinates in React Native?
I've got an object containing the lat and lng of my companys facilities. I've also got an object containing the lat and lng of the user's current location. What I'd like to do is iterate through the object with the location data of the sites, and calculate the closest one to the user's location. I'd like to get the kilometers between the two as well as the time it would take to drive the distance.
I've been looking at Google's Geometry API but can not figure out how to use this in React Native, if it's possible.
My question is what I should do to best achieve this? Can I somehow use the Google Geometry API?
Edit: I don't have to do this in the app, preferably I'd like to do so, but if it's not possible I could simply make a fetch to my PHP API if there is a better solution for PHP.
Solution 1:[1]
calculateDistance(lattitude1, longittude1,lattitude2,longittude2)
{
const toRadian = n => (n * Math.PI) / 180
let lat2 = lattitude2
let lon2 = longittude2
let lat1 = lattitude1
let lon1 = longittude1
console.log(lat1, lon1+"==="+lat2, lon2)
let R = 6371 // km
let x1 = lat2 - lat1
let dLat = toRadian(x1)
let x2 = lon2 - lon1
let dLon = toRadian(x2)
let a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadian(lat1)) * Math.cos(toRadian(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
let d = R * c
console.log("distance==?",d)
return d
}
calculateDistance(25.3773009 68.3034496,25.3947972 68.3312881);
Solution 2:[2]
Try out this updated working 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>
);
}
}
Solution 3:[3]
This is an example of calculating the distance between two points, using ts
This is not 100% accurate, if you need a more accurate calculation please go and check here
If you need more calculation then you can use this lib
Note: I created these methods based on the lib and while searching, I did not want to install the complete library because all I need is distance calculation.
type UseDistanceTypes = {
from: { latitude: number; longitude: number };
to: { latitude: number; longitude: number };
};
const earthRadius = 6378137;
const toRadius = (value: number): number => (value * Math.PI) / 180;
export const useDistance = ({ from, to }: UseDistanceTypes): number => {
const distance =
Math.acos(
Math.sin(toRadius(to.latitude)) * Math.sin(toRadius(from.latitude)) +
Math.cos(toRadius(to.latitude)) * Math.cos(toRadius(from.latitude)) * Math.cos(toRadius(from.longitude) - toRadius(to.longitude)),
) * earthRadius;
return Math.round(convertDistance(distance, 'km'));
};
// Convert to a different unit
const convertDistance = (meters: number, targetUnit: keyof typeof distanceConversion = 'm'): number => {
return distanceConversion[targetUnit] * meters;
};
const distanceConversion = {
m: 1,
mi: 1 / 1609.344,
km: 0.001,
cm: 100,
mm: 1000
};
You can put it inside a memo, but I do not see any benefits in my case because the lat and long props will always change. I am using here just javascript (typescript) so it can be used in react too, btw i am using this method in my React native app.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali Raza Khan |
| Solution 2 | Rahul |
| Solution 3 | Muhamet Smaili |
