Created
July 7, 2019 23:25
-
-
Save jacoby/61b3ba9690501d80dc985aa8573c1129 to your computer and use it in GitHub Desktop.
Library to interface with Google's Geolocation, Geocoding and TimeZone APIs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package GoogleGeo; | |
# interfaces with Google Geolcation API | |
# https://developers.google.com/maps/documentation/geolocation/intro | |
use strict; | |
use warnings; | |
use utf8; | |
use feature qw{ postderef say signatures state }; | |
no warnings qw{ experimental::postderef experimental::signatures }; | |
use Carp; | |
use Data::Dumper; | |
use Exporter qw(import); | |
use Getopt::Long; | |
use JSON::XS; | |
use LWP::Protocol::https; | |
use LWP::UserAgent; | |
our @EXPORT = qw{ | |
geocode | |
geolocate | |
timezone | |
}; | |
my $json = JSON::XS->new->pretty; | |
my $agent = LWP::UserAgent->new; | |
sub timezone ( $Google_API_key, $obj ) { | |
croak unless defined $Google_API_key; | |
if ( ! defined $obj->{time}) { | |
$obj->{time} = DateTime->now()->epoch; | |
} | |
my $url = 'https://maps.googleapis.com/maps/api/timezone/json?key=' | |
. $Google_API_key; | |
my $latlng = join ',', $obj->{lat}, $obj->{lng}; | |
$url .= '&location=' . $latlng; | |
$url .= '×tamp=' . $obj->{time}; | |
say STDERR $json->encode($obj); | |
say STDERR $url; | |
my $r = $agent->post($url); | |
if ( $r->is_success ) { | |
my $j = $r->content; | |
my $o = $json->decode($j); | |
say STDERR $j; | |
return $o; | |
} | |
return {}; | |
} | |
sub geocode ( $Google_API_key, $obj ) { | |
croak unless defined $Google_API_key; | |
my $url = 'https://maps.googleapis.com/maps/api/geocode/json?key=' | |
. $Google_API_key; | |
my $latlng = join ',', $obj->{lat}, $obj->{lng}; | |
$url .= '&latlng=' . $latlng; | |
my $object = { latlng => $latlng }; | |
my $r = $agent->post($url); | |
if ( $r->is_success ) { | |
my $j = $r->content; | |
my $o = $json->decode($j); | |
return $o; | |
} | |
return {}; | |
} | |
sub geolocate ($Google_API_key) { | |
my $url = 'https://www.googleapis.com/geolocation/v1/geolocate?key=' | |
. $Google_API_key; | |
my $object = {}; | |
my $r = $agent->post( $url, $object ); | |
if ( $r->is_success ) { | |
my $j = $r->content; | |
my $o = $json->decode($j); | |
return { | |
lat => $o->{location}{lat}, | |
lng => $o->{location}{lng}, | |
acc => $o->{accuracy}, | |
}; | |
} | |
return {}; | |
} | |
'here'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment