I am trying to develop a "divide and conquer" algorithm to determine squares of latitude and longitude.
I wish to start with an 800 mile x 800 mile box around the UK. Then divide this into four squares, and then recursively repeating this process until the squares are 25 miles square. This will then be used to filter out unwanted results from a proximity search in a database of locations.
However, the algorithm I have which applies an offset to a lat/long (see below code), is giving me problems. I have tried other ones, too, but with much the same results. I think it may be my understanding of applying a coordinate system to a sphere.
I would expect that with a starting point, moving east 800 miles, then moving west 800 miles would result in being returned to (approx) the same location. However, this is not the case:
var coord =
{
lat : 60.678413562308236,
lng : -12.5
};
// Apply a distance and bearing to a set of coords.
var addOffset = function(coord, distance, angle)
{
// Earth Radius
//var radius = 6378.14; // KM
var radius = 3958.8; // Miles
// Degrees to Radians
var lat = coord.lat * (Math.PI/180);
var lng = coord.lng * (Math.PI/180);
var bearing = angle * (Math.PI/180);
var lat2 = Math.asin(Math.sin(lat)*Math.cos(distance/radius) + Math.cos(lat)*Math.sin(distance/radius)*Math.cos(bearing));
var lng2 = lng + Math.atan2(Math.sin(bearing)*Math.sin(distance/radius)*Math.cos(lat), Math.cos(distance/radius)-Math.sin(lat)*Math.sin(lat2));
// back to degrees
lat2 = lat2 * (180/Math.PI);
lng2 = lng2 * (180/Math.PI);
return { lat : lat2, lng : lng2};
}
console.log("start");
console.log(coord);
console.log("Move 800 miles east");
coord = addOffset(coord, 800, 90.0) // East
console.log(coord);
console.log("Move 800 miles west");
coord = addOffset(coord, 800, 270.0) // West
console.log(coord);
Further, when "walking" an 800 mile square around the UK, and plotting the points on a Google Map, I get big problems! The below is starting north-west, going south 800 miles, then going east 800 miles, then north 800 miles, then west 800 miles. As you can see, it's gone quite wrong:
Here's a fiddle (couldn't work out how to get the map working on a code snippet here):
https://jsfiddle.net/leetaylor/aoxnsqeu/6/
Could anyone explain where I'm going wrong? Is it possible to divide up geography into squares using lat/longs?