Alright, so this is for a Magic Mirror module I am making. Its a wrapper for the Traccar Service to be deployed on magic mirror. I needed to calculate the farthest two points on the map from an object containing multiple locations of each registered user. Then once I have the farthest two points on the map, I could calculate the middle point between them to set it as center of the map. Now I am working on the zooming of the map to include all the markers on the map.. anyways, for the problem I explained here the solution was found after little bit of research. Here it goes.
function toRadians (deg){ // Helper function
return deg * (Math.PI/180);
}
function toDegrees (rad){ // Helper function
return rad * (180/Math.PI);
}
function distance (obj){ // Helper function from https://www.movable-type.co.uk/scripts/latlong.html | http://mathforum.org/library/drmath/view/51822.html
var R = 6371e3; // metres
var φ1 = obj[0][0];
var φ2 = obj[1][0];
var Δφ = obj[1][0]-obj[0][0];
var Δλ = obj[1][1]-obj[0][1];
var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return (R * c);
}
function midPoints(obj){ // Helper functions (which I modified for the specifications) from https://stackoverflow.com/questions/477591/algorithm-to-find-two-points-furthest-away-from-each-other | https://www.movable-type.co.uk/scripts/latlong.html | http://mathforum.org/library/drmath/view/51822.html
var self = this;
var solution = {"start": [], "end": [], "distance": 0};
for (i = 0; i < obj.length; i++) {
for (j = i+1; j < obj.length; j++) {
var newpoint = [
[
self.toRadians(obj[i][0]),
self.toRadians(obj[i][1])
],
[
self.toRadians(obj[j][0]),
self.toRadians(obj[j][1])
]
];
var distance = self.distance(newpoint);
if (distance > solution.distance){
solution = {"start": [obj[i][0],obj[i][1]], "end": [obj[j][0],obj[j][1]], "distance": distance}
}
}
}
var Bx = Math.cos(solution.end[0]) * Math.cos(solution.end[1]-solution.start[1]);
var By = Math.cos(solution.end[0]) * Math.sin(solution.end[1]-solution.start[1]);
var latMid = Math.atan2(Math.sin(solution.start[0]) + Math.sin(solution.end[0]),Math.sqrt((Math.cos(solution.start[0])+Bx)*(Math.cos(solution.start[0])+Bx) + By*By ) );
var lonMid = solution.start[1] + Math.atan2(By, Math.cos(solution.start[0]) + Bx);
return {"lat": self.toDegrees(latMid), "lon": self.toDegrees(lonMid), "distance": solution.distance};
}