function distance(lat1, lng1, lat2, lng2, feet = false){
let p = 0.017453292519943295, c = Math.cos;
let r = 12742000*Math.asin(Math.sqrt(0.5-c((lat1-lat2)*p)/2+c(lat2*p)*c(lat1*p)*(1-c((lng1-lng2)*p))/2));
if(feet)r *= 1/0.3048;
return r
}
function Vehicle(color, year, make, model, lat = null, lng = null){
this.color = color; this.year = year; this.make = make; this.model = model; this.lat = lat; this.lng = lng;
this.distanceTo = (latLng, feet = false)=>{
return distance(this.lat, this.lng, latLng.lat, latLng.lng, feet);
}
}
function Lot(lat, lng, capacity){
this.lat = lat; this.lng = lng; this.capacity = capacity;
this.vehicles = [];
this.addVehicle = vehicle=>{
if(this.vehicles.length < this.capacity){
vehicle.lat = this.lat; vehicle.lng = this.lng; this.vehicles.push(vehicle);
}
return this;
}
this.removeVehicle = vehicle=>{
const v = this.vehicles, x = v.indexOf(vehicle);
if(x !== -1)v.splice(x, 1);
return this;
}
this.distanceTo = (latLng, feet = false)=>{
return distance(this.lat, this.lng, latLng.lat, latLng.lng, feet);
}
}
function sortDistances(distances, feet = false){
const d = [...distances], r = [], sortIt = (a, b)=>Object.values(a)[0]-Object.values(b)[0];
let n, a;
for(let lot of d){
n = -1; a = [];
for(let l of d){
n++;
if(l !== lot)a.push({[n]:lot.distanceTo(l, feet)});
}
a.sort(sortIt); r.push(a);
}
return r;
}
const lot1 = new Lot(47.581148063351534, -122.24032639373426, 1);
const lot2 = new Lot(47.583444521820496, -122.2447443008423, 1);
const lot3 = new Lot(47.583544521820333, -122.2447543008222, 35);
const vehicle1 = new Vehicle('yellow', 1979, 'Ford', 'Pinto');
const vehicle2 = new Vehicle('red', 2020, 'Ferrari', '812 Superfast');
lot1.addVehicle(vehicle1); lot2.addVehicle(vehicle2);
const lots = [lot1, lot2, lot3]; // so you can get the lots by index later
const d = sortDistances(lots);
console.log(d); // an Array of Arrays of Objects with lots indexes as keys and meters as values