HTML and CSS Reference
In-Depth Information
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 calcu-
late 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.
Summary
This chapter showed you how to use geolocation in the browser to generate a position that can be used to display
an interactive map. With the ability to track a position and display and update interactive maps, a number of
augmented-reality games can be built in the browser. This includes scavenger hunts, geocaching, proximity-
based games, and more. The hope is that putting geolocation tools in your arsenal can open up a new world of
HTML5 games that breaks gaming outside of its normal confines.
Search WWH ::




Custom Search