I have written a script to grab some info from google geocoder using perl and json. This example below grabs address info using an airport abbr.
use JSON;
use LWP::Simple;
my $geo_url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=PHL";
my $response = get($geo_url);
my $json = decode_json($response);
my $location = $json->{results}[0]->{geometry}->{location};
my $address = $json->{results}[0]->{formatted_address};
print "<br />Latitude: ".$location->{lat}." Longiude: ".$location->{lng};
print "<br />Address: ".$address;
I can grab individual parts of the address_component array by using:
$json->{results}[0]{address_components}[0]->{short_name};
$json->{results}[0]{address_components}[1]->{short_name};
but what I really want to do is get the city, state and zip (postal_code). to do this I need to loop through the address_components and run something like this:
for (keys $json->{results}[0]{address_components}) {
if ($json->{results}[0]{address_components}[$i]->types[0] eq "postal_code") {
print "Zip: ".$json->{results}[0]{address_components}[$i]->{short_name};
}
}
Obviously this is not valid code but I wanted to explain what I am trying to do. It’s the loop I can’t get to work. I’ve tried a lot of configurations and I keep getting an array length of 1 even though the array item length is 6.
Based on
$json->{results}[0]{address_components}holds a reference to an array. While you can technically callkeyson an array reference to get a list of indexes in recent versions of Perl, it’s simpler just to get a list of the array’s elements in this case (and most other cases too).Might be better to look at all the types.