272 Part III — Google Map Hacks
Note that even with this formula, the exact distance may be different because the earth is not a
perfect sphere (it is slightly “flat” and therefore wider at the equator than at the poles), but the
difference for most small routes is so small that it is not noticeable.
Rather than performing the calculation within JavaScript on the host, the information is deter-
mined by the backend script as it returns the route point information. The function accepts
four arguments, the long/lat pairs for the start and end points. This is called for each pair dur-
ing the point extraction loop in the getroute()function. By adding each point pair distance
together, the distance for the entire route can be calculated:
sub latlngdistance
{
my ($xdeg1,$ydeg1,$xdeg2,$ydeg2) = @_;
my ($x1,$y1,$x2,$y2) = (deg2rad($xdeg1),
deg2rad($ydeg1),
deg2rad($xdeg2),
deg2rad($ydeg2));
my $radius = 6371;
my $latdistance = $x2 - $x1;
my $lngdistance = $y2 - $y1;
my $a = sin($latdistance/2) * sin($latdistance/2) +
cos($x1) * cos($x2) * sin($lngdistance/2) * sin($lngdistance/2);
my $c = 2 * atan2(sqrt($a), sqrt(1-$a));
my $d = $radius * $c;
return $d;
}
The same process could have been carried out within the browser, which would have also
enabled the application to show a live distance calculation as the route was being calculated,
but this information is easier and more straightforward to calculate within the backend func-
tion and also takes some load off of the browser.
Using the Application
The best way to get to know the application in use is, of course, to try it out. The basics of the
system (saving a route, listing available routes, and then loading a single route) can easily be
shown, at least in terms of how they look.
First, Figure 13-3 shows the application in its initial state, showing the map (centered, for a
change, on Grantham).
Click New Route to enable routing and select the first point for your route. Click further
points until you have a route displayed onscreen, as shown here in Figure 13-4. Note that the
route title and a description have also been given here.
In Figure 13-5 you can see the final route when saved, here showing its final distance and the
start and end markers.
Figure 13-6 shows the list of available routes, including the one just created.