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。
我如何将字符串分割成两个只有坐标的字符串?
https://i.stack.imgur.com/xFfVP.jpg String res = "34.0522° N, 118.2437° W"
到String res1 = "34.0522"
和String res2 = "118.2437"
Thanks in advance
可以使用Google Map Geocoding 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);
}
这将很难,因为您正在寻找的内容不在链接的HTML代码中:https://www.google.com/#q=latitude+and+longitude+Paris
它看起来像ajax注入甚至编码从: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ψ
\x3cdiv class\x3d\x22_XWk\x22\x3e48.8566\xb0 N, 2.3522\xb0 E\x3c/div\x3e
获取城市经度和纬度的更好方法是使用Google Map API:
https://maps.googleapis.com/maps/api/geocode/json?address=Paris一个简单的方法是从NuGet安装库或在Package Manager Console中编写
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();
}