如何使用geonames API获取城市名称?

时间:2012-05-20 21:42:31

标签: c# xml windows-phone-7 geonames

如何使用API​​搜索地理名称并获取城市名称和坐标? 链接到他们的API

1 个答案:

答案 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下都有lnggeoname元素。使用LINQ to XML(在命名空间声明中包含System.LinqSystem.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);
}

当然,您可以选择以不同方式使用这些值,并且您可能希望将LatLong解析为双打。

相关问题