开发者

Using JSON, WCF et al. with Google geocoding - is it really necessary?

开发者 https://www.devze.com 2023-01-17 16:03 出处:网络
I have a requirement to geocode data using Google\'s geocoding service. Google\'s geocoding services aren\'t as friendly to consumption via .NET as, say Bing\'s (no surprise there) so while I could go

I have a requirement to geocode data using Google's geocoding service. Google's geocoding services aren't as friendly to consumption via .NET as, say Bing's (no surprise there) so while I could go all out with ContractDataSerializers, WCF, JSON and a whole other pile of acronyms is there anything wrong with something like the below if all I need is, say, latitude and longitude viz.

st开发者_运维知识库ring url = String.Format("http://maps.google.com/maps/api/geocode/xml?address=blah&region=ie&sensor=false", HttpUtility.UrlEncode(address));

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(url);
XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/GeocodeResponse/result");

if (xmlNodeList != null)
{
   // Do something here with the information
}

Other than a lot of upfront development effort what precisely will the other approach buy? I am very comfortable with WCF, DataContracts, ServiceContracts etc. but I can't see what they'll bring to the table here...


Use the GoogleMap Control project on codeplex : http://googlemap.codeplex.com/

It has class for doing geocoding with Google : http://googlemap.codeplex.com/wikipage?title=Google%20Geocoder&referringTitle=Documentation .


I'd use XDocument with WebRequest. Following example might help.

public static GeocoderLocation Locate(string query)
{
    WebRequest request = WebRequest.Create("http://maps.google.com/maps?output=kml&q="
        + HttpUtility.UrlEncode(query));

    using (WebResponse response = request.GetResponse())
    {
        using (Stream stream = response.GetResponseStream())
        {
            XDocument document = XDocument.Load(new StreamReader(stream));

            XNamespace ns = "http://earth.google.com/kml/2.0";

            XElement longitudeElement = document.Descendants(ns + "longitude").FirstOrDefault();
            XElement latitudeElement = document.Descendants(ns + "latitude").FirstOrDefault();

            if (longitudeElement != null && latitudeElement != null)
            {
                return new GeocoderLocation
                {
                    Longitude = Double.Parse(longitudeElement.Value, CultureInfo.InvariantCulture),
                    Latitude = Double.Parse(latitudeElement.Value, CultureInfo.InvariantCulture)
                };
            }
        }
    }

    return null;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号