Chapter 13 — I Need to Get To... 271
In addition to calculating the total distance, the XML for each point also needs to be gener-
ated. As with other elements, the information is embedded into attributes for a suitable named
XML tag:
my $distance = 0;
my $seq = 0;
my ($lastx,$lasty) = (undef,undef);
while (my $row = $sth->fetchrow_hashref())
{
$seq++;
printf(‘<point lat=”%f” lng=”%f”/>’,
$row->{lat},
$row->{lng},
);
if ($seq >= 2)
{
$distance += latlngdistance($lastx,
$lasty,
$row->{lat},
$row->{lng});
}
($lastx,$lasty) = ($row->{lat},$row->{lng});
}
$sth->finish();
The final part of the process is to return the final distance, and for convenience both metric
and imperial measures are provided:
printf(‘
$distance,
($distance/1.609344));
print(“\n”);
}
The actual calculation of the distance is complicated and takes place in a separate function.
Calculating Distance
When returning a given route it is nice to be able to supply a distance from the start point to
the destination point. There is no easy way to determine this information; Google does not
supply a convenient method.
The only way to determine the information is to take the points given and calculate the dis-
tance. This is itself difficult because latitude and longitude are measures of degrees on the sur-
face of the earth. To calculate the distance between points, what you actually have to calculate
is the distance between two points on a sphere (effectively the portion of the circumference on
the surface of the earth).
Describing, in detail, the exact method required is beyond the scope of this book, but the equa-
tion is called the Haversine formula. To determine the distance between two points, you calcu-
late the arc on the surface of the earth, using the radius of the earth (in kilometers) as a base
reference. You may want to visit the Movable Type Scripts web site (http://www.movable-
type.co.uk/scripts/LatLong.html).