Server-side Geocoding using the Google Maps API

Here is a simple class for server-side geocoding. This implementation uses the basic csv data transfer format so it is just geocoding. It can easily be extended to return more data by switching to the json data transfer format. It can also be easily extended to support reverse geocoding.

    public interface IGeocodingService
    {
        IEnumerable<OrderedPoint> Geocode(string[] addresses);
    }

    public class GeocodingService : IGeocodingService
    {
        private readonly IConfigService config;
        private const string REQUEST_TEMPLATE = "http://maps.google.com/maps/geo?q={0}&output=csv&oe=utf8&sensor=false&key={1}";

        public GeocodingService(IConfigService config)
        {
            this.config = config;
        }

        public IEnumerable<OrderedPoint> Geocode(string[] addresses)
        {
            return addresses.Where(a => !string.IsNullOrEmpty(a)).Select(a => Geocode(a));
        }

        public OrderedPoint Geocode(string address)
        {
            WebRequest request = WebRequest.Create(String.Format(REQUEST_TEMPLATE, address.Replace(' ', '+'), config.GoogleMapsAPIKey()));
            var response = request.GetResponse() as HttpWebResponse;
            var reader = new StreamReader(response.GetResponseStream());
            var parts = reader.ReadToEnd().Split(',');
            return new OrderedPoint
                       {
                           Address = address,
                           LatLon = new LatLon { Lat = double.Parse(parts[2]), Lon = double.Parse(parts[3]) }
                       };
        }
    }

 and the usage is:

    var geocoder = new GeocodingService(new ConfigService());
    var point = geocoder.Geocode("17 Burchell St Carina, Queensland");

 

kick it on DotNetKicks.com

Comments

Comments are closed