2012-12-05 31 views

回答

3

這是一個快速perl函數來獲取任意地址的經度和緯度。它使用CPAN和Google的Geocode API中的LWP :: Simple和JSON。如果你想要完整的數據,你可以做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

所以你在短短1分鐘內回答了你自己的問題? :) –

+0

我想發佈它,因爲我找了一段時間才弄明白,想要挽救下一個人。 – jpgunter

+0

好的。 [你可以在問題中提供答案,並問這個問題的措辭是「有更好的答案」。](http://meta.stackexchange.com/questions/17845/etiquette-for-answering-your-own-questions ) –

1

沒有爲谷歌地理編碼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斷裂,很容易發現並報告。

+0

非常好,正如@Oesor指出的那樣,您可以使用Geo :: Coder :: Many來比較幾個API的結果。 – jpgunter

+0

有沒有辦法從圖書館獲取「超限狀態」信息? –

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 }); 
} 
+0

不錯,我喜歡比較許多差異服務的想法。 – jpgunter

相關問題