Search code examples
perlgeolocationlatitude-longitudepostal-code

Perl to get location (longitude+latitude), plus post codes


There is this from another poster. (jpgunter)https://stackoverflow.com/users/1857927/jpgunter

use strict;
use LWP::Simple; # from CPAN
use JSON qw( decode_json ); # from CPAN

sub getLatLong($){
  my ($address) = @_;

  my $format = "json"; #can also to 'xml'

  my $geocodeapi = "https://maps.googleapis.com/maps/api/geocode/";

  my $url = $geocodeapi . $format . "?sensor=false&address=" . $address;

  my $json = get($url);

  my $d_json = decode_json( $json );

  my $lat = $d_json->{results}->[0]->{geometry}->{location}->{lat};
  my $lng = $d_json->{results}->[0]->{geometry}->{location}->{lng};

  return ($lat, $lng);
}

It looks to be doing what I want, but... is anyone able to explain where I put the address to run it and where does the output go?

I have to run through about 5000 cities from another file for a 'non-scholastic' project I am working on and obviously the thought of doing manually is horrific. I also have only done minimal perl in the last 7 years so absolutely any help would be great. I already have LWP 6.04 and JSON 2.53 installed. if I could use an input file, rotate this through (with postcodes where it shows it). That line would be on... "formatted_address" : "Geelong West VIC 3218, Australia", Just not sure how to get the 3218 there.

The original post is here... Get the Latitude and Longitude of an address using perl and Google's Geocode API


Solution

  • This is a file with a subroutine that gets the long/lat data from the Google API and returns these two values. However, the subroutine is not being called so the script does nothing.

    The following change to the beginning of the script will get input from the command line and return the data to terminal:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use LWP::Simple; # from CPAN
    use JSON qw( decode_json ); # from CPAN
    
    # get command line input
    my $address = $ARGV[0];
    
    # get latitude/longitude and output
    my ($lat, $long) = getLatLong( $address );
    print "lat: $lat, long: $long\n";
    
    
    sub getLatLong($){
      my ($address) = @_;
    
      my $format = "json"; #can also to 'xml'
    
    ...
    

    You can then call the script as follows:

    $ long_lat_script.pl '25 Jackson street, Pretoria, South Africa'
    

    As to the comments about usage policy of this API, it depends on what you want to use it for. You do indeed need to display a map when using this API; however, it is allowed (and recommended by Google) to do a batch collection of such data if you need it in your site instead of repeatedly asking for the same data. I once used this API in a similar manner for around 5000 addresses. You can read some more about this here.