Resolving geographical entities with Scala
Here is a chunk of Scala code for getting lat/lon coordinates of geographical locations (cities or villages) using the wonderful geonames.org webservice which allows to search for geo entities by name. The getCoords() method returns a triple of (resolved entity name, lat, lon). The countryCode parameter is optional and will limit the search within the country when specified. The webservice often returns more than one result, in this case the method will return the coordinates of the first one.
import scala.xml._ import java.io._ import java.net.{URLEncoder, URL} def getCoords(query:String, countryCode:String):(String, Double, Double) = { val geonames = XML.loadString(readUrl( "http://ws.geonames.org/search?featureClass=P&q=" + URLEncoder.encode(query) + (if (countryCode != null) ("&country=" + countryCode) ))) if ((geonames \ "geoname").size > 0) { var firstGeoname = (geonames \ "geoname").first ((firstGeoname \ "name").first.text + " (" + (firstGeoname \ "countryCode").first.text + ")", (firstGeoname \ "lat").first.text.toDouble, (firstGeoname \ "lng").first.text.toDouble) } else { null } } def readUrl(url:String) = { val in = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "utf-8")) val response = new StringBuilder var inputLine:String = null do { inputLine = in.readLine if (inputLine != null) response.append(inputLine) } while (inputLine != null) in.close response.toString }
Calling getCoords(“Neuchatel”, “CH”) returns a triple (Neuchâtel (CH),46.99179,6.931).





