This is a tutorial for using the
OpenCage geocoding API
in Perl.
Topics covered in this tutorial
- General Background
- Agent Skill
- installing Geo::Coder::OpenCage
- Forward geocoding
- Reverse geocoding
- Geocoding a list of places
- Further reading
Background
The code examples below will use your geocoding API key once you
log in.
Before we dive in to the tutorial
- Sign up for an OpenCage geocoding API key.
- Play with the demo page, so that you see the actual response the API returns.
- Browse the API reference, so you understand the optional parameters, best practices, possible response codes, and the rate limiting on free trial accounts.
Working with AI?
We offer an
Agent Skill
to make it easy for AI to quickly learn about our geocoding API.
Agent Skill / Working with AI
Are you developing with AI?
We offer an Agent Skill that includes a reference file specifically about developing code to access our API via Perl.
Install the OpenCage Perl geocoding module
# install with cpanm
$ cpanm Geo::Coder::OpenCage
Please note: by default
Geo::Coder::OpenCage
makes all requests via https. Please ensure you are able to
make https requests, or specify the optional
http => 1
parameter to the
new
method when creating the
Geo::Coder::OpenCage
object to make http rather than https requests.
Forward Geocoding - 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#optional-params
#
# note: no need to URI encode location, module does that for you
#
my $response = $Geocoder->geocode(
location => "Псковская улица, Санкт-Петербург, Россия",
language => "ru",
countrycode => "ru",
);
Reverse Geocoding - coordinates to address
use Geo::Coder::OpenCage;
my $Geocoder = Geo::Coder::OpenCage->new(
api_key => 'YOUR-API-KEY',
abbrv => 1,
);
my $response = $Geocoder->reverse_geocode(lat => -22.6792, lng => 14.5272);
# get first result
my $result = $response->{results}[0];
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"
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 $response = $Geocoder->geocode(
location => $place
);
# $response is a hashref
# see format:
# https://opencagedata.com/api#response
my $msg = $response->{status}->{message};
if ($msg eq 'OK'){
$results{$place} = $response->{results};
} else {
warn "failed to geocode $place : $msg";
}
}
2,500 geocoding API requests/day - No credit card required