代码改变世界

C# 根据地址调用 Google Map 服务得到经纬度

2012-12-18 18:57  音乐让我说  阅读(351)  评论(0编辑  收藏  举报

直接贴代码了:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace MvcUI.Extensions
{
    public static class LocalisationUtils
    {
        /// <summary>
        /// 根据地址调用 Google 服务得到经纬度
        /// </summary>
        /// <param name="postcode"></param>
        /// <returns></returns>
        public static List<string> GeocodeGoogle(string postcode)
        {
            var longlat = new List<string>();
            var req = (HttpWebRequest)WebRequest.Create(string.Format("http://www.google.com/uds/GlocalSearch?q={0}&v=1.0", postcode));
            using (var resp = req.GetResponse())
            using (var respStream = resp.GetResponseStream())
            using (var reader = new StreamReader(respStream))
            {
                var response = reader.ReadToEnd();
                var serializer = new JavaScriptSerializer();
                var deserialized = (Dictionary<string, object>)serializer.DeserializeObject(response);
                var responseData = (Dictionary<string, object>)deserialized["responseData"];
                var results = (object[])responseData["results"];
                try
                {
                    var resultsData = (Dictionary<string, object>)results[0];
                    longlat.Add(resultsData["lat"].ToString());
                    longlat.Add(resultsData["lng"].ToString());
                    longlat.Add(resultsData["title"].ToString());
                }
                catch (Exception)
                {
                    longlat.Add("0");
                    longlat.Add("0");
                    longlat.Add("No Result");
                }
                return longlat;
            }
        }
    }
}

 

谢谢浏览!