Calculating the Position between Two Points
When you start building games with geolocation, one of the first difficulties you’ll face is the problem to calculate the distance between two latitudes and longitudes. Whether this is to detect the proximity between players or distance to a goal, this is something that you definitely must do.
On the client side, Google’s Map v3 API provides a static method under google.maps.geometry.spherical called computeDistanceBetween, which takes two LatLng objects and returns the distance in meters.
If you don’t have an API readily handy to do the calculation for you, your can use the Haversine distance formula (http://en.wikipedia.org/wiki/Haversine_formula) to calculate the distance on a sphere between two points.
There are a number of resources for this formula in JavaScript, but one of the best available on the web is at www.movable-type.co.uk/scripts/latlong.html. It provides a succinct Haversine formula in JavaScript that takes in lat1, lon1 lat2, and lon2 and outputs the distance between the two in kilometers:
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
You can plug this formula directly into a method in your code to calculate the distance between two points.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access