在Perl中,如何从任意地址获取纬度和经度?可以使用外部API。
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);
}
return @{ $$d_json{results}[0]{geometry}{location} }{qw/lat long/};
,中间箭头可以忽略。 - amonuse Geo::Coder::Bing;
use Geo::Coder::Googlev3;
use Geo::Coder::Mapquest;
use Geo::Coder::OSM;
use Geo::Coder::Many;
use Geo::Coder::Many::Util qw( country_filter );
### Geo::Coder::Many object
my $geocoder_many = Geo::Coder::Many->new( );
$geocoder_many->add_geocoder({ geocoder => Geo::Coder::Googlev3->new });
$geocoder_many->add_geocoder({ geocoder => Geo::Coder::Bing->new( key => 'GET ONE' )});
$geocoder_many->add_geocoder({ geocoder => Geo::Coder::Mapquest->new( apikey => 'GET ONE' )});
$geocoder_many->add_geocoder({ geocoder => Geo::Coder::OSM->new( sources => 'mapquest' )});
$geocoder_many->set_filter_callback(country_filter('United States'));
$geocoder_many->set_picker_callback('max_precision');
for my $location (@locations) {
my $result = $geocoder_many->geocode({ location => $location });
}
Google Geocoding API有一个包装器模块,Geo::Coder::Google:
#!/usr/bin/env perl
use strict;
use utf8;
use warnings qw(all);
use Data::Printer;
use Geo::Coder::Google;
my $geocoder = Geo::Coder::Google->new(apiver => 3);
my $location = $geocoder->geocode(location => 'Hollywood and Highland, Los Angeles, CA');
p $location->{geometry}{location};
\ {
lat 34.101545,
lng -118.3386871
}
通常最好使用现成的CPAN模块,因为它由CPAN测试者服务支持,所以如果API出现问题,很容易发现并报告。