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.
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.
Precise distance calculation can be done using getPreciseDistance() function which calculates the distance between two geo coordinates. This method is more accurate then getDistance, especially for long distances but it is also slower. It is using the Vincenty inverse formula for ellipsoids.
from math import cos, asin, sqrt, pi def distance(lat1, lon1, lat2, lon2): p = pi/180 a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2 return 12742 * asin(sqrt(a)) #2*R*asin... And for the sake of completeness: Haversine on Wikipedia.
The npm package geolib https://github.com/manuelbieh/geolib has several methods that can help you do this; getDistance, findNearest, and orderByDistance.
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>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With