如何使用geonames API获取城市名称?
答
当然,这完全取决于您想要执行的实际搜索。假设您想在英国找到所有以Lon
开头的地点。将执行该搜索(作为一个例子,多少可以为真正的搜索更改)的网址是:
http://api.geonames.org/search?name_startsWith=lon&country=GB&maxRows=10&username=demo
可以弹出,在您的浏览器,并查看结果:
<geonames style="MEDIUM">
<totalResultsCount>334</totalResultsCount>
<geoname>
<toponymName>London</toponymName>
<name>London</name>
<lat>51.50853</lat>
<lng>-0.12574</lng>
<geonameId>2643743</geonameId>
<countryCode>GB</countryCode>
<countryName>United Kingdom</countryName>
<fcl>P</fcl>
<fcode>PPLC</fcode>
</geoname>
<geoname>
<toponymName>Lone</toponymName>
<name>Lone</name>
<lat>58.33333</lat>
<lng>-4.88333</lng>
<geonameId>2643732</geonameId>
<countryCode>GB</countryCode>
<countryName>United Kingdom</countryName>
<fcl>P</fcl>
<fcode>PPL</fcode>
</geoname>
<!-- and so on ... -->
</geonames>
注意您需要每个geoname
下的lat
和lng
元素。随着LINQ到XML(包括在您的命名空间声明System.Linq
和System.Linq.Xml
):
var xml = XElement.Load("http://api.geonames.org/search?name_startsWith=lon&country=GB&maxRows=10&username=demo");
var locations = xml.Descendants("geoname").Select(g => new {
Name = g.Element("name").Value,
Lat = g.Element("lat").Value,
Long = g.Element("lng").Value
});
foreach (var location in locations)
{
Console.WriteLine("{0}: {1}, {2}", location.Name, location.Lat, location.Long);
}
当然,你可以选择不同的方式使用这些值,你可能要解析Lat
和Long
成双打。
这样做。谢谢! – Megaoctane