aboutsummaryrefslogtreecommitdiffstats
path: root/perllib/FixMyStreet/Geocode
diff options
context:
space:
mode:
Diffstat (limited to 'perllib/FixMyStreet/Geocode')
-rw-r--r--perllib/FixMyStreet/Geocode/Bing.pm67
-rw-r--r--perllib/FixMyStreet/Geocode/Google.pm85
-rw-r--r--perllib/FixMyStreet/Geocode/OSM.pm116
3 files changed, 268 insertions, 0 deletions
diff --git a/perllib/FixMyStreet/Geocode/Bing.pm b/perllib/FixMyStreet/Geocode/Bing.pm
new file mode 100644
index 000000000..cfeffc856
--- /dev/null
+++ b/perllib/FixMyStreet/Geocode/Bing.pm
@@ -0,0 +1,67 @@
+#!/usr/bin/perl
+#
+# FixMyStreet::Geocode::Bing
+# Geocoding with Bing for FixMyStreet.
+#
+# Copyright (c) 2011 UK Citizens Online Democracy. All rights reserved.
+# Email: matthew@mysociety.org; WWW: http://www.mysociety.org/
+
+package FixMyStreet::Geocode::Bing;
+
+use strict;
+use Encode;
+use File::Slurp;
+use File::Path ();
+use LWP::Simple;
+use Digest::MD5 qw(md5_hex);
+
+# string STRING CONTEXT
+# Looks up on Bing Maps API, and caches, a user-inputted location.
+# Returns array of (LAT, LON, ERROR), where ERROR is either undef, a string, or
+# an array of matches if there are more than one. The information in the query
+# may be used to disambiguate the location in cobranded versions of the site.
+sub string {
+ my ( $s, $c, $params ) = @_;
+ my $url = "http://dev.virtualearth.net/REST/v1/Locations?q=$s&c=en-GB"; # FIXME nb-NO for Norway
+ $url .= '&mapView=' . $params->{bounds}[0] . ',' . $params->{bounds}[1]
+ if $params->{bounds};
+ $url .= '&userLocation=' . $params->{centre} if $params->{centre};
+
+ my $cache_dir = FixMyStreet->config('GEO_CACHE') . 'bing/';
+ my $cache_file = $cache_dir . md5_hex($url);
+ my $js;
+ if (-s $cache_file) {
+ $js = File::Slurp::read_file($cache_file);
+ } else {
+ $url .= '&key=' . FixMyStreet->config('BING_MAPS_API_KEY');
+ $js = LWP::Simple::get($url);
+ $js = encode_utf8($js) if utf8::is_utf8($js);
+ File::Path::mkpath($cache_dir);
+ File::Slurp::write_file($cache_file, $js) if $js;
+ }
+
+ if (!$js) {
+ return { error => _('Sorry, we could not parse that location. Please try again.') };
+ } elsif ($js =~ /BT\d/) {
+ return { error => _("We do not cover Northern Ireland, I'm afraid, as our licence doesn't include any maps for the region.") };
+ }
+
+ $js = JSON->new->utf8->allow_nonref->decode($js);
+ if ($js->{statusCode} ne '200') {
+ return { error => _('Sorry, we could not find that location.') };
+ }
+
+ my $results = $js->{resourceSets}->[0]->{resources};
+ my ( $error, @valid_locations, $latitude, $longitude );
+ foreach (@$results) {
+ my $address = $_->{name};
+ next unless $_->{address}->{countryRegion} eq 'United Kingdom'; # FIXME This is UK only
+ ( $latitude, $longitude ) = @{ $_->{point}->{coordinates} };
+ push (@$error, $address);
+ push (@valid_locations, $_);
+ }
+ return { latitude => $latitude, longitude => $longitude } if scalar @valid_locations == 1;
+ return { error => $error };
+}
+
+1;
diff --git a/perllib/FixMyStreet/Geocode/Google.pm b/perllib/FixMyStreet/Geocode/Google.pm
new file mode 100644
index 000000000..c37a750a2
--- /dev/null
+++ b/perllib/FixMyStreet/Geocode/Google.pm
@@ -0,0 +1,85 @@
+#!/usr/bin/perl
+#
+# FixMyStreet::Geocode
+# The geocoding functions for FixMyStreet.
+#
+# Copyright (c) 2010 UK Citizens Online Democracy. All rights reserved.
+# Email: matthew@mysociety.org; WWW: http://www.mysociety.org/
+
+package FixMyStreet::Geocode::Google;
+
+use strict;
+use Encode;
+use File::Slurp;
+use File::Path ();
+use LWP::Simple;
+use Digest::MD5 qw(md5_hex);
+
+# string STRING CONTEXT
+# Looks up on Google Maps API, and caches, a user-inputted location.
+# Returns array of (LAT, LON, ERROR), where ERROR is either undef, a string, or
+# an array of matches if there are more than one. The information in the query
+# may be used to disambiguate the location in cobranded versions of the site.
+sub string {
+ my ( $s, $c, $params ) = @_;
+
+ my $url = 'http://maps.google.com/maps/geo?q=' . $s;
+ $url .= '&ll=' . $params->{centre} if $params->{centre};
+ $url .= '&spn=' . $params->{span} if $params->{span};
+ $url .= '&gl=' . $params->{country} if $params->{country};
+ $url .= '&hl=' . $params->{lang} if $params->{lang};
+
+ my $cache_dir = FixMyStreet->config('GEO_CACHE') . 'google/';
+ my $cache_file = $cache_dir . md5_hex($url);
+ my $js;
+ if (-s $cache_file) {
+ $js = File::Slurp::read_file($cache_file);
+ } else {
+ # For some reason adding gl=uk is no longer sufficient to make google
+ # think we are in the UK for some locations so we explictly add UK to
+ # the address. We do it here so as not to invalidate existing cache
+ # entries
+ if ( $c->cobrand->country eq 'GB'
+ && $url !~ /,\+UK/
+ && $url !~ /united\++kingdom$/ )
+ {
+ if ( $url =~ /&/ ) {
+ $url =~ s/&/,+UK&/;
+ } else {
+ $url .= ',+UK';
+ }
+ }
+ $url .= '&sensor=false&key=' . FixMyStreet->config('GOOGLE_MAPS_API_KEY');
+ $js = LWP::Simple::get($url);
+ $js = encode_utf8($js) if utf8::is_utf8($js);
+ File::Path::mkpath($cache_dir);
+ File::Slurp::write_file($cache_file, $js) if $js && $js !~ /"code":6[12]0/;
+ }
+
+ if (!$js) {
+ return { error => _('Sorry, we could not parse that location. Please try again.') };
+ } elsif ($js =~ /BT\d/) {
+ # Northern Ireland, hopefully
+ return { error => _("We do not currently cover Northern Ireland, I'm afraid.") };
+ }
+
+ $js = JSON->new->utf8->allow_nonref->decode($js);
+ if ($js->{Status}->{code} ne '200') {
+ return { error => _('Sorry, we could not find that location.') };
+ }
+
+ my $results = $js->{Placemark};
+ my ( $error, @valid_locations, $latitude, $longitude );
+ foreach (@$results) {
+ next unless $_->{AddressDetails}->{Accuracy} >= 4;
+ my $address = $_->{address};
+ next unless $c->cobrand->geocoded_string_check( $address );
+ ( $longitude, $latitude ) = @{ $_->{Point}->{coordinates} };
+ push (@$error, $address);
+ push (@valid_locations, $_);
+ }
+ return { latitude => $latitude, longitude => $longitude } if scalar @valid_locations == 1;
+ return { error => $error };
+}
+
+1;
diff --git a/perllib/FixMyStreet/Geocode/OSM.pm b/perllib/FixMyStreet/Geocode/OSM.pm
new file mode 100644
index 000000000..b1becaa7a
--- /dev/null
+++ b/perllib/FixMyStreet/Geocode/OSM.pm
@@ -0,0 +1,116 @@
+#!/usr/bin/perl
+#
+# FixMyStreet:Geocode::OSM
+# OpenStreetmap forward and reverse geocoding for FixMyStreet.
+#
+# Copyright (c) 2011 Petter Reinholdtsen. Some rights reserved.
+# Email: pere@hungry.com
+
+package FixMyStreet::Geocode::OSM;
+
+use warnings;
+use strict;
+
+use Memcached;
+use mySociety::Config;
+use LWP::Simple;
+use XML::Simple;
+
+my $osmapibase = "http://www.openstreetmap.org/api/";
+my $nominatimbase = "http://nominatim.openstreetmap.org/";
+
+
+sub lookup_location {
+ my ($latitude, $longitude, $zoom) = @_;
+ my $url =
+ "${nominatimbase}reverse?format=xml&zoom=$zoom&lat=$latitude&lon=$longitude";
+ my $key = "OSM:lookup_location:$url";
+ my $result = Memcached::get($key);
+ unless ($result) {
+ my $j = LWP::Simple::get($url);
+ if ($j) {
+ Memcached::set($key, $j, 3600);
+ my $ref = XMLin($j);
+ return $ref;
+ } else {
+ print STDERR "No reply from $url\n";
+ }
+ return undef;
+ }
+ return XMLin($result);
+}
+
+sub _osmxml_to_hash {
+ my ($xml, $type) = @_;
+ my $ref = XMLin($xml);
+ my %tags;
+ if ('ARRAY' eq ref $ref->{$type}->{tag}) {
+ map { $tags{$_->{'k'}} = $_->{'v'} } @{$ref->{$type}->{tag}};
+ return \%tags;
+ } else {
+ return undef;
+ }
+}
+
+sub get_object_tags {
+ my ($type, $id) = @_;
+ my $url = "${osmapibase}0.6/$type/$id";
+ my $key = "OSM:get_object_tags:$url";
+ my $result = Memcached::get($key);
+ unless ($result) {
+ my $j = LWP::Simple::get($url);
+ if ($j) {
+ Memcached::set($key, $j, 3600);
+ return _osmxml_to_hash($j, $type);
+ } else {
+ print STDERR "No reply from $url\n";
+ }
+ return undef;
+ }
+ return _osmxml_to_hash($result, $type);
+}
+
+# A better alternative might be
+# http://www.geonames.org/maps/osm-reverse-geocoder.html#findNearbyStreetsOSM
+sub get_nearest_road_tags {
+ my ( $cobrand, $latitude, $longitude ) = @_;
+ my $inforef = lookup_location($latitude, $longitude, 16);
+ if (exists $inforef->{result}->{osm_type}
+ && 'way' eq $inforef->{result}->{osm_type}) {
+ my $osmtags = get_object_tags('way',
+ $inforef->{result}->{osm_id});
+ unless ( exists $osmtags->{operator} ) {
+ $osmtags->{operatorguess} = $cobrand->guess_road_operator( $osmtags );
+ }
+ return $osmtags;
+ }
+ return undef;
+}
+
+sub closest_road_text {
+ my ( $cobrand, $latitude, $longitude ) = @_;
+ my $str = '';
+ my $osmtags = get_nearest_road_tags( $cobrand, $latitude, $longitude );
+ if ($osmtags) {
+ my ($name, $ref) = ('','');
+ $name = $osmtags->{name} if exists $osmtags->{name};
+ $ref = " ($osmtags->{ref})" if exists $osmtags->{ref};
+ if ($name || $ref) {
+ $str .= _('The following information about the nearest road might be inaccurate or irrelevant, if the problem is close to several roads or close to a road without a name registered in OpenStreetMap.') . "\n\n";
+ $str .= sprintf(_("Nearest named road to the pin placed on the map (automatically generated using OpenStreetMap): %s%s"),
+ $name, $ref) . "\n\n";
+
+ if (my $operator = $osmtags->{operator}) {
+ $str .= sprintf(_("Road operator for this named road (from OpenStreetMap): %s"),
+ $operator) . "\n\n";
+ } elsif ($operator = $osmtags->{operatorguess}) {
+ $str .= sprintf(_("Road operator for this named road (derived from road reference number and type): %s"),
+ $operator) . "\n\n";
+ }
+ }
+ }
+ return $str;
+}
+
+1;
+