I’m trying to calculate the distance between the user and the items listed on my repeater. I have a repeater that shows the cars for sale and the distance they are from the user, however the repeater does not show the distance, it shows a NaN error.
I’ve tried several ways but I can’t solve it. Can someone help me?
I have in my database the fields:
•latitude (number)
•longitude (number)
•address (address).
This is my code
import wixData from ‘wix-data’;
import wixWindow from ‘wix-window’;
$w.onReady(function () {
});
function calculateDistance (lat1,lon1,lat2,lon2) {
function rad(x) {return x * Math.PI/180;}
let R = 6378.137;
let dLat = rad(lat2 - lat1);
let dLong = rad(lon2 - lon1);
let a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLong/2) * Math.sin(dLong/2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d.toFixed(3);
}
export function RepeaterCars_itemReady($item, itemData, index) {
wixWindow.getCurrentGeolocation()
.then((obj)=>{
let latitude = obj.coords.latitude;
let longitude = obj.coords.longitude;
console.log("my location is: " + latitude + longitude);
let lat1 = latitude
let lon1 = longitude
let lat2 = itemData.lat;
let lon2 = itemData.lon;
let distance = calculateDistance (lat1, lon1, lat2, lon2)
$item("#TextDistance").text = distance;
})
.catch( (error) => {
let errorMsg = error;
});
}