The following example downloads a sample dataset that contains the node that represents the Big Ben in London and prints out information about that node. Therefore, it opens a stream to retrieve the sample file from our server and creates an OsmXmlIterator using the InputStream as constructor argument.
We can then iterate through the elements using a for-each loop. The iterator returns EntityContainers that wrap the actual objects. We check whether the object is a node using the getType() method and then retrieve the actual object using the getEntity() method and cast it to a OsmNode.
Once we have the OsmNode, we can print its id and the coordinate. Using another for loop, we can also print each tag by retrieving the i-th tag using the getTag(i) method.
| public static void main(String[] args) throws IOException |
| { |
| // Define a query to retrieve some data |
| String query = "http://osmtestdata.topobyte.de/big-ben.osm"; |
| // Open a stream |
| InputStream input = new URL(query).openStream(); |
| // Create an iterator for XML data |
| OsmIterator iterator = new OsmXmlIterator(input, false); |
| // Iterate all elements |
| for (EntityContainer container : iterator) { |
| // Check if the element is a node |
| if (container.getType() == EntityType.Node) { |
| // Cast the entity to OsmNode |
| OsmNode node = (OsmNode) container.getEntity(); |
| // Print basic information |
| System.out.println("id: " + node.getId()); |
| System.out.println("latitude: " + node.getLatitude()); |
| System.out.println("longitude: " + node.getLongitude()); |
| // Also print all tags |
| System.out.println("tags:"); |
| for (int i = 0; i < node.getNumberOfTags(); i++) { |
| OsmTag tag = node.getTag(i); |
| System.out.println(tag.getKey() + " = " + tag.getValue()); |
| } |
| } |
| } |
| } |
Here's the output:
id: 1802652184
latitude: 51.5006617
longitude: -0.1245829
tags:
amenity = clock
display = analog
faces = 4
historic = technical_monument
name = Big Ben
support = tower
tourism = attraction
visibility = area
wikipedia = en:Big Ben