GeoNames Search (2)

March 4th, 2007

In this demonstration, a simple C# application will be created to search the GeoNames database and display the results in tabular form. Let’s begin by creating a new Windows Application in Visual C# Express.

A simple form can be set up to capture the necessary input parameters: location name, country, and the number of rows returned. At the bottom of the form, add a DataGridView control to display the XML results. My completed form looks like this:

GeoNamesSearch1

Since we are going to be dealing with XML in our code, add this using statement to the code:

 

using System.Xml;

 

In this example, we only need to add code to the button to perform the search. Double-click on the button itself to create a Click event in the code view. Here is how I performed the search:

 

string searchPhrase = txtSearch.Text;
string searchCountry = txtCountry.Text;
int maxRows = 0;
try
{
  maxRows = Convert.ToInt16(txtMaxRows.Text);
}
catch
{
  MessageBox.Show("Enter a valid number of rows!");
}
if (maxRows > 0)
{
  string url = "http://ws.geonames.org/search?q=";
  url += searchPhrase + "&maxRows=" + maxRows.ToString() + "&country=" + searchCountry;
  lblURL.Text = url; 
 
  try
  {
    DataSet dsResults = new DataSet("xmlResults");
    dsResults.ReadXml(url);
    grdResults.DataSource = dsResults;
    grdResults.DataMember = "geoname";
  }
  catch
  {
    MessageBox.Show("Error in connection or URL!");
  }
}

 

In the above code, we perform several steps. We first capture and validate the input parameters from the form’s controls (txtSearch, txtCountry, txtMaxRows). We then construct the URL as we discussed in the previous post. Finally, we use the URL to perform the search and return the results in an XML dataset. The results are easily displayed in the DataGridView for display.

Here is what the results for an “Oakland” search looks like:

GeoNamesSearch2

C# and the .NET framework provide easy access for obtaining and using XML data. As the above example shows, it makes no difference if the XML data is on your local hard drive or a website. Further processing of XML is also very straightforward and will be explored in future projects. For example, the GeoNames search results could be added onto a map or exported to a local file.

Continue to part 3