You don't say what you're using to display the data returned by Google (what are dbg
and p
?) but it's certainly not a string: it's a complex hash containing nested hashes and arrays. Using Data::Dump
to display it reveals the contents and makes them simple to access and manipulate.
This program uses a fixed-up version of your own subroutine to fetch information for the Royal Observatory in Greenwich. It then prints the long_name
value of each line in the address_components
array. It also dumps the entire data structure using Data::Dump
so that you can see what is being returned.
If you prefer, the Data::Dumper
may also be used. It is a core module for Perl 5 and so won't need installing, but the layout of the text it produces is inferior to that of Data::Dump
.
use strict;
use warnings;
use Geo::Coder::Google;
use Data::Dump;
my $geocoder = Geo::Coder::Google->new(apiver => 3);
my $location = map_latlon_to_loc(51.4768777, 0);
my $address = $location->{address_components};
print $_->{long_name}, "\n" for @$address;
print "\n\n";
dd $location;
sub map_latlon_to_loc {
my ($lat, $lng) = @_;
$geocoder->reverse_geocode(latlng => "$lat,$lng");
}
output
Blackheath Avenue
Greater London
United Kingdom
SE10 8XJ
London
{
address_components => [
{
long_name => "Blackheath Avenue",
short_name => "Blackheath Ave",
types => ["route"],
},
{
long_name => "Greater London",
short_name => "Gt Lon",
types => ["administrative_area_level_2", "political"],
},
{
long_name => "United Kingdom",
short_name => "GB",
types => ["country", "political"],
},
{
long_name => "SE10 8XJ",
short_name => "SE10 8XJ",
types => ["postal_code"],
},
{ long_name => "London", short_name => "London", types => ["postal_town"] },
],
formatted_address => "Blackheath Avenue, London SE10 8XJ, UK",
geometry => {
bounds => {
northeast => { lat => 51.4770228, lng => 0.0005404 },
southwest => { lat => 51.4762273, lng => -0.0001147 },
},
location => { lat => 51.4766277, lng => 0.0002212 },
location_type => "APPROXIMATE",
viewport => {
northeast => { lat => 51.4779740302915, lng => 0.00156183029150203 },
southwest => { lat => 51.4752760697085, lng => -0.00113613029150203 },
},
},
types => ["route"],
}