Michael Lee Michael Lee - 1 year ago 93
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;

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?


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

Thanks in advance

Answer Source

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download