如何使用API搜索地理名称并获取城市名称和坐标? 链接到他们的API
答案 0 :(得分:4)
当然,这完全取决于您想要执行的实际搜索。假设您要查找以Lon
开头的英国所有地点。将执行此搜索的URL(例如,对于真实搜索可能会发生很大变化)是:
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>
请注意,您希望每个lat
下都有lng
和geoname
元素。使用LINQ to 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
解析为双打。