简体   繁体   中英

c# google maps coordinates

I've been using this code for a while in my application to get latitude and longitude for certain addresses :

private string geoCode(string query)
    {
        WebRequest request = WebRequest.Create("http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address="
                 + HttpUtility.UrlEncode(query));

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

                XElement longitudeElement = document.Descendants("lng").FirstOrDefault();
                XElement latitudeElement = document.Descendants("lat").FirstOrDefault();

                if (longitudeElement != null && latitudeElement != null)
                {
                    return latitudeElement.Value.ToString() + ", " + longitudeElement.Value.ToString();
                }
            }
        }

        return null;
    }

Its been working till now. Now when I start the program it doesnt return anything, I've tried multiple different queries and still returns null as a result.

Variable query contains address which i wrote in my windows forms c# textbox. I push the button and this code executes. Does anybody have an idea why it isn't working anymore?

A couple of things that you can help you narrow down the problem

  1. Take the api address and location from your text box. Directly paste the url in chrome and see if you get any result

    http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=address_you_are_trying

I tried with few address and I got back response.

  1. If everything is fine at this end, then figure out your c# code. It could be you are not parsing the correct xml element. If you do not want to parse the xml, you can change the xml parameter to JSON and desiralize in to a JSON object to get the properties more easily like this

    http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=Ealing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM