Perl Geocoding Tutorial

The code examples below will use your API key once you log in.

This is a tutorial for using the OpenCage Geocoding API in Perl.

Before we dive in to the tutorial ...

You will need to sign up for an OpenCage API key.

Spend two minutes ...

Ok, ready?

Install the OpenCage Perl geocoding library

# install with cpanm
$ cpanm Geo::Coder::OpenCage

Forward Geocode - address to coordinates

use Geo::Coder::OpenCage;

my $Geocoder = Geo::Coder::OpenCage->new(
    api_key => 'YOUR-API-KEY',
);

# see the full list of optional parameters:
# https://opencagedata.com/api#forward-opt
my $result = $Geocoder->geocode(
    location => "Псковская улица, Санкт-Петербург, Россия",
    language => "ru",
    countrycode => "ru",
);

Batch geocode addresses

use Geo::Coder::OpenCage;

my @places = ('London', 'Paris', 'Berlin');
my %results;

# loop through the list, geocoding each individually
foreach my $place (@places){
    my $result = $Geocoder->geocode(
        location => $place
    );
    # $result is a hashref
    # see format:
    # https://opencagedata.com/api#response

    my $msg = $result->{status}->{message};
    if ($msg eq 'OK'){
        $results{$place} = $result;
    } else {
        warn "failed to geocode $place : $msg";
    }
}

Reverse Geocode - coordinates to address

use Geo::Coder::OpenCage;

my $Geocoder = Geo::Coder::OpenCage->new(
    api_key => 'YOUR-API-KEY',
    abbrv => 1,
);

my $result = $Geocoder->reverse_geocode(lat => -22.6792, lng => 14.5272);

my $nicename = $result->{formatted};
# $nicename is now "Beryl's Restaurant, Woermann St, Swakopmund, Namibia"

# see full list of all the annotations
# https://opencagedata.com/api#annotations

my $geohash = $result->{annotations}->{geohash};
# $geohash is now "k7fqfx6h5jbq5tn8tnpn"

Further Reading

Start your free trial

2,500 API requests per day.

No credit card required.