从asp.net MVC调用Google地图Web服务API

时间:2011-04-18 02:51:59

标签: google-maps-api-3

我找到了以下代码来调用Google地图网络服务API: -

public static class Geocoder{
private static string _GoogleMapsKey = Config.getAppSetting(“GoogleMapsKey”);

public static Geolocation? ResolveAddress(string query)

{if (string.IsNullOrEmpty(_GoogleMapsKey))
_GoogleMapsKey = ConfigurationManager.AppSettings["GoogleMapsKey"];

string url = “http://maps.google.com/maps/geo?q={0}&output=xml&key=” + _GoogleMapsKey; 

url = String.Format(url, query);

XmlNode coords = null;

try{

string xmlString = GetUrl(url);

XmlDocument xd = new XmlDocument();

xd.LoadXml(xmlString);

XmlNamespaceManager xnm = new XmlNamespaceManager(xd.NameTable);

coords = xd.GetElementsByTagName(“coordinates”)[0];

}catch { }

Geolocation? gl = null;

if (coords != null){

string[] coordinateArray = coords.InnerText.Split(‘,’);

if (coordinateArray.Length >= 2)

{gl = new Geolocation(Convert.ToDecimal(coordinateArray[1].ToString()), 
Convert.ToDecimal(coordinateArray[0].ToString()));

}

}return gl;

}public static Geolocation? ResolveAddress(string address, string city, string state, 
string postcode, string country)

{return ResolveAddress(address + “,” + city + “,” + state + “,” + postcode + ” “ + 
country);}

private static string GetUrl(string url)

{string result = string.Empty;

System.Net.WebClient Client = new WebClient();

using (Stream strm = Client.OpenRead(url))

{StreamReader sr = new StreamReader(strm);

result = sr.ReadToEnd();

}return result;}}

public struct Geolocation

{public decimal Lat;

public decimal Lon;

public Geolocation(decimal lat, decimal lon){

Lat = lat;

Lon = lon;}

public override string ToString()
{return “Latitude: “ + Lat.ToString() + ” Longitude: “ + Lon.ToString();

}public string ToQueryString()

{return “+to:” + Lat + “%2B” + Lon;}}

**所以我创建了一个包含上述代码的新模型类,为了测试我的工作,我在控制器中编写了以下内容

Geocoder.ResolveAddress(“University road”,”rajkot”,”gujarat”,”",”India”)

但我仍然不知道如何创建相关视图来显示地图? 在此先感谢您的帮助。**

1 个答案:

答案 0 :(得分:1)

我发布了一个名为“google-maps”包装库的开源项目。

有了它,您可以轻松查询Google地图的地理编码,路线,海拔,以及将来的地方。

使用此库,您只能从地理编码中获取数据。没有包含UI控件。

请在此处查看 - http://code.google.com/p/google-maps/