2016-11-12 50 views
-2
   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); 

我使用上面的代碼從谷歌獲取某個位置並將顯示經緯度的文本框複製到字符串res中。每次運行代碼時,我都會收到一個nullReferenceException。將div從一個網站分配到一個字符串

而我怎樣才能將字符串拆分爲兩個字符串與座標只?

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

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

在此先感謝

回答

1

您可以使用谷歌地圖API地理編碼。這個API會向你發送一個Json文件。 像這樣與newtonsoft JSON庫:

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

    } 
+0

非常感謝你,它終於工作了。 –

0

這將是困難的,因爲你正在尋找的內容是不是在鏈接的HTML代碼:https://www.google.com/#q=latitude+and+longitude+Paris

它看起來像是注入的阿賈克斯編碼從:https://www.google.com/search?q=latitude+and+longitude+paris&bav=on.2,or.r_cp.&cad=b&fp=1&biw=1920&bih=677&dpr=1&tch=1&ech=1&psi=

\\x3cdiv class\\x3d\\x22_XWk\\x22\\x3e48.8566\\xb0 N, 2.3522\\xb0 E\\x3c\/div\\x3e 

一個更好的方式來獲得的經度和緯度的城市是使用谷歌地圖API:

https://maps.googleapis.com/maps/api/geocode/json?address=Paris

0

一個簡單的方法是包被安裝後你可以得到緯度從的NuGet安裝庫或包管理器寫控制檯

Install-Package GoogleMaps.LocationServices 

和日誌真的很容易因爲使用其內置功能

static void Main(string[] args) 
     { 
      string locationName = Console.ReadLine(); 

      var location = new GoogleLocationService(); 
      var point = location.GetLatLongFromAddress(locationName); 

      Console.WriteLine(point.Latitude); 
      Console.WriteLine(point.Longitude); 
      Console.Read(); 

     } 
相關問題