=head1 NAME Geo::LatLon2Place - convert latitude and longitude to nearest place =head1 SYNOPSIS use Geo::LatLon2Place; my $db = Geo::LatLon2Place->new ("/var/lib/mydb.cdb"); =head1 DESCRIPTION This is a simple-purpose module that tries to do one job: find the nearest placename for a point on earth. It doesn't claim to do a perfect job, but it tries to be simple to set up, simple to use and be fast. =head2 BUILDING AND SETTING UP To build this module, you need tinycdb, a cdb implementation by Michael Tokarev, or a compatible library. On GNU/Debian-based systems you can get this by executing F. After install the module, you need to generate a database using the F command. Currently, it accepts various databases from geonames (L, note the license), for example, F, which lists all places with population 500 or more: wget https://download.geonames.org/export/dump/cities500.zip unzip cities500.zip geo-latlon2place-makedb --geonames-gazetteer cities500.txt ll2place.cdb This will create a file F that you can use for lookups with this module. At the time of this writing, the F database results in about a 10MB file while the F database results in about 120MB. =over 4 =cut package Geo::LatLon2Place; use common::sense; use Carp (); BEGIN { our $VERSION = 0.01; require XSLoader; XSLoader::load __PACKAGE__, $VERSION; eval 'sub TORAD() { ' . ((atan2 1,0) / 180) . ' }'; } sub new { my ($class, $path) = @_; open my $fh, "<", $path or Carp::croak "$path: $!\n"; my $self = bless [$fh, ""], $class; cdb_init $self->[1], fileno $self->[0] and Carp::croak "$path: unable to open as cdb file\n"; (my ($magic, $version), $self->[2], $self->[3]) = unpack "a4VVV", cdb_get $self->[1], ""; $magic eq "SRGL" or Carp::croak "$path: not a Geo::LatLon2Place file"; $version == 1 or Carp::croak "$path: version mismatch (got $version, expected 1)"; $self } sub DESTROY { my ($self) = @_; cdb_free $self->[1]; } sub lookup { my ($self, $lat, $lon, $radius) = @_; $radius ||= $self->[2]; $radius = int +($radius + $self->[2] - 1) / $self->[2]; my $coslat = cos abs $lat * TORAD; my $blat = int $self->[3] * $coslat; my $cx = int (($lon + 180) * $blat / 360); my $cy = int (($lat + 90) * $self->[3] / 180); my ($min, $res) = (1e00); for my $y ($cy - $radius .. $cy + $radius) { for my $x ($cx - $radius .. $cx + $radius) { for (unpack "(C/a*)*", cdb_get $self->[1], pack "s< s<", $x, $y) { my ($plat, $plon, $w, $data) = unpack "s< s< C a*"; $plat = $plat * ( 90 / 32767); $plon = $plon * (180 / 32767); my $dx = ($lon - $plon) * TORAD * $coslat; my $dy = ($lat - $plat) * TORAD; my $d2 = ($dx * $dx + $dy * $dy) * $w; $d2 >= $min or ($min, $res) = ($d2, $data); } } } $res } =head1 AUTHOR Marc Lehmann http://home.schmorp.de/ =cut 1