在Perl中如何从任意地址获取lat和long?可以使用外部API。
答案 0 :(得分:3)
这是一个快速perl函数,用于获取任意地址的纬度和经度。它使用CPAN的LWP :: Simple和JSON以及Google的Geocode API。如果你想要完整的数据,可以使用json或xml,这个使用json,只需抓取并返回lat和long。
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);
}
答案 1 :(得分:2)
您可以使用Geo :: Coder :: Many来比较不同的服务,找到认为最准确的服务。在农村和城市地址的混合中,我(美国)好运。
use 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 });
}
答案 2 :(得分:1)
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 Testers服务支持,因此,如果API中断,则很容易发现和报告。