涂聚文--信息智能化学习者,豆腐渣工程投诉者

C# sample for Google Geocoding API (JSON output)

2015-12-18 12:41:51 人评论 次浏览

: nothing at of , which is

分类:CSharp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the address to validate:");
            var address = Console.ReadLine();
            NetGoogleGeocoding geoCoder = new NetGoogleGeocoding();
            var response = geoCoder.GoogleGeocode(address);
            Console.WriteLine("*********** validation complete *****************");
            Console.WriteLine(string.Format("House Number ---- {0}",response.GeoCodes[0].HouseNumber));
            Console.WriteLine(string.Format("Street Address -- {0}",response.GeoCodes[0].StreetAddress));
            Console.WriteLine(string.Format("City ------------ {0}",response.GeoCodes[0].City));
            Console.WriteLine(string.Format("County ---------- {0}",response.GeoCodes[0].County));
            Console.WriteLine(string.Format("State ----------- {0}",response.GeoCodes[0].State));
            Console.WriteLine(string.Format("Zip ------------- {0}",response.GeoCodes[0].Zip));
            Console.WriteLine(string.Format("Country --------- {0}",response.GeoCodes[0].Country));
            Console.WriteLine(string.Format("Full Address ---- {0}",response.GeoCodes[0].FullAddress));
            if (response.GeoCodes[0].Types.Count() > 1)
            {
                Console.WriteLine(string.Format("Types ----------- {0},{1}", response.GeoCodes[0].Types[0], response.GeoCodes[0].Types[1]));
            }
            else
            {
                Console.WriteLine(string.Format("Types ----------- {0}", response.GeoCodes[0].Types[0]));
            }
            Console.WriteLine(string.Format("Location Type---- {0}",response.GeoCodes[0].LocationType));
            Console.WriteLine(string.Format("Latitude -------  {0}",response.GeoCodes[0].Latitude.ToString()));
            Console.WriteLine(string.Format("Longitude-------- {0}",response.GeoCodes[0].Longitude.ToString()));
            Console.WriteLine(string.Format("Status   -------- {0}", response.GeoCodes[0].Status));
            Console.ReadLine();
         }
    }
 /// <summary>
 ///   .Net utility for google geocoding API
 /// </summary>
 public class NetGoogleGeocoding {
        public GeocodeJsonResponse GoogleGeoCodeResponse;
  const string GoogleGeoCodeJsonServiceUrl = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true&components=country:US";
        public NetGoogleGeocoding()
        {
            GoogleGeoCodeResponse = new GeocodeJsonResponse()
            {
                GeoCodes = new List<geocode>()
            };
  }
  /// <summary>
  ///   Performs Geocode and returns Object
  /// </summary>
  /// <param name="address"> 
        public GeocodeJsonResponse GoogleGeocode(string address)
        {
            using (var cli = new WebClient())
            {
                var addressToValidate = string.Format(GoogleGeoCodeJsonServiceUrl, HttpUtility.UrlEncode(address));
                var response = cli.DownloadString(new Uri(addressToValidate));
                return HydrateJson(response);
           }
  }
  /// <summary>
  /// generic method to read json values from json string
  /// </summary>
  /// <param name="token"> 
  /// <param name="field"> 
  /// <returns> </returns>
  static string GetJsonNodeValue(JToken token, string field) {
   return token["address_components"].Children().Any(x => x["types"].Values<string>().Contains(field))
        ? token["address_components"].Children().First(x => x["types"].Values<string>().Contains(field))["short_name"].Value<string>()
        : string.Empty;
  }
        GeocodeJsonResponse HydrateJson(string jsonResponse)
        {
   var results = (JObject) JsonConvert.DeserializeObject(jsonResponse);
   foreach(
   var googleGeoCode in
      results["results"].Children().Select(
         token =>
   new Geocode {
      HouseNumber = GetJsonNodeValue(token, "street_number"),
      StreetAddress = GetJsonNodeValue(token, "route"),
      City = GetJsonNodeValue(token, "locality"),
      County = GetJsonNodeValue(token, "administrative_area_level_2"),
      State = GetJsonNodeValue(token, "administrative_area_level_1"),
      Zip = GetJsonNodeValue(token, "postal_code"),
      Country = GetJsonNodeValue(token, "country"),
      FullAddress = token["formatted_address"].Value<string>(),
      Types = token["types"].Values<string>().ToList(),
      LocationType = token["geometry"]["location_type"].Value<string>(),
      Latitude = token["geometry"]["location"]["lat"].Value<float>(),
      Longitude = token["geometry"]["location"]["lng"].Value<float>(),
      Status = string.Format("{0}", token["geometry"]["location_type"].Value<string>())
   })) {
    GoogleGeoCodeResponse.GeoCodes.Add(googleGeoCode);
   }
   return GoogleGeoCodeResponse;
  }
 }

    public class GeocodeJsonResponse
    {
        public List<geocode> GeoCodes { get; set; }
    }
    public class Geocode
    {
        public string HouseNumber { get; set; }
        public string StreetAddress { get; set; }
        public string City { get; set; }
        public string County { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public string Country { get; set; }
        public string FullAddress { get; set; }
        public List<string> Types { get; set; }
        public string LocationType { get; set; }
        public float Latitude { get; set; }
        public float Longitude { get; set; }
        public string Status { get; set; }
    }

}