Michael Lee Michael Lee - 23 days ago 4
C# Question

Assign div from a website to a string

string locationName = Console.ReadLine();
string url = "https://www.google.com/#q=latitude+and+longitude+" + locationName;

HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(url);
HtmlNode rateNode = doc.DocumentNode.SelectSingleNode("//div[@class='_XWk']");
string res = rateNode.InnerText;
Console.WriteLine(res);


I am using the code above to get a certain location from google and copy the textbox displaying the latitude and longitude into the string res. Every time when I run the code I receive a nullReferenceException.

And how can I split the string into two strings with the coordinates only?

http://imgur.com/a/7useZ

String res = "34.0522° N, 118.2437° W"
into
String res1 = "34.0522"
and
String res2 = "118.2437"


Thanks in advance

Answer

You can use Google Map Geocoding API. This API will send you a Json file. Like this with newtonsoft Json library:

    String fileName = "LosAngeles";
    WebRequest webRequest = WebRequest.Create("http://maps.google.com/maps/api/geocode/json?address=" + fileName);
    WebResponse response = webRequest.GetResponse();
    using (Stream responseStream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
        String json = reader.ReadToEnd();
        JObject jsonObject = JObject.Parse(json);
        String lat = (string)jsonObject["results"][0]["geometry"]["location"]["lat"];
        String lng = (string)jsonObject["results"][0]["geometry"]["location"]["lng"];
        Console.WriteLine(lat + " : " + lng);

    }
Comments