Contents Prev: Iterators and readers: counting elements Next: Writing data: OsmOutputStreams

Using tags: counting businesses

The three basic data types all implement the OsmEntity interface so that we can access an object's tags by iterating them using a for loop. The tags are provided as a list by default to minimize computational overhead in situtations where tags are not needed or where the sequential representation suffices. For example when converting from one file format to another, or when extracting a subset for an area from a bigger dataset, we don't care about the meaning of the tags but just pass them to an output stream.

In many situations however, the sequential representation is not very useful. Since any object may not have multiple tags with the same key, its tags can be inserted into a dictionary data structure for convenient access.

For this purpose, osm4j provides the OsmModelUtil helper class that offers a method getTagsAsMap() that can be used to retrieve an entity's tags as a Map<String,String>.

The following example makes use of this method to count the number of restaurants, cafes and pubs within a bounding box:

  public static void main(String[] args) throws IOException
  {
    // Define a query to retrieve some data
    String query = "http://www.overpass-api.de/api/xapi?*[bbox="
        + "13.465661,52.504055,13.469817,52.506204]";
 
    // Open a stream
    InputStream input = new URL(query).openStream();
 
    // Create an iterator for XML data
    OsmIterator iterator = new OsmXmlIterator(input, false);
 
    // Initialize the counters
    int numRestaurants = 0;
    int numCafes = 0;
    int numPubs = 0;
 
    // Iterate objects, ignore non-node objects
    for (EntityContainer container : iterator) {
      if (container.getType() == EntityType.Node) {
        OsmNode node = (OsmNode) container.getEntity();
 
        // Get the node's tags as a map
        Map<String, String> tags = OsmModelUtil.getTagsAsMap(node);
 
        // Get the value for the 'amenity' key
        String amenity = tags.get("amenity");
 
        // Ignore nodes without such a tag
        if (amenity == null) {
          continue;
        }
 
        // Increment counters depending on the type
        if (amenity.equals("restaurant")) {
          numRestaurants++;
        } else if (amenity.equals("cafe")) {
          numCafes++;
        } else if (amenity.equals("pub")) {
          numPubs++;
        }
      }
    }
 
    // Print the results
    System.out.println("restaurants: " + numRestaurants);
    System.out.println("cafes: " + numCafes);
    System.out.println("pubs: " + numPubs);
  }

Here's the output:

restaurants: 11
cafes: 10
pubs: 4
Contents Prev: Iterators and readers: counting elements Next: Writing data: OsmOutputStreams