C# – How to use geonames API to get city name

cgeonameswindows-phone-7xml

How can i search the geonames using their API and get city name and coordinates?
Link to their API

Best Answer

Of course it depends entirely on the actual search you want to perform. Let's say you want to find all locations in Great Britain that start with Lon. The URL that will perform this search (as an example, much may change for a real search) is:

http://api.geonames.org/search?name_startsWith=lon&country=GB&maxRows=10&username=demo

You can pop that in your browser and see the results:

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

Note that you want the lat and lng elements under each geoname. With LINQ to XML (include System.Linq and System.Linq.Xml in your namespace declarations):

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

Of course you may choose to use these values differently, and you may want to parse Lat and Long into doubles.