Overpass-turbo: How to find amenity inside amenity

I’ve tried to find amenity=school mapped inside of another amenity=school. The container might be a closed way or relation, the inside one might be a node, way or relation.
If overlapping areas get returned it would also be OK.

I have read the documentation but couldn’t build a working query. Maybe someone has done this already and could help me out? Thanks!

This can’t be done directly. (area) includes bordering features, not only overlapping features. More computation is needed to discard them. Be aware that the feature being used to find inside will be returned as well. around isn’t helpful, as it only includes features inside that extend to the border.

[out:json][timeout:25];
nwr({{bbox}})[amenity=school]->.all;
foreach.all->.this
{
  nwr.all(area.this)->.candidates;
  if (candidates.count(nodes)>0)
  {
    node.candidates;
    out geom;
    .this out geom;
  }
  (wr.candidates; - .this;)->.candidatesareas;
  if (candidatesareas.count(wr)>0)
  {
    (way.candidatesareas; way(r.candidatesareas);)->.candidatessegments;
    node(w.candidatessegments);
    node._(area.this)->.candidatessegmentspts;
    (way.this; way(r.this););
    node(w)->.thispts;
    (.candidatessegmentspts; - node.candidatessegmentspts.thispts;);
    if (count(nodes)>0)
    {
      way.candidatessegments(bn)->.matchessegments;
      (way.matchessegments.candidatesareas; rel.candidatesareas(bw.matchessegments););
      out geom;
      .this out geom;
    };
  };
};

Didn’t use foreach again in the last part. Assuming always more efficient to avoid nested loops.
Simpler to do this in other GIS software eg QGIS. Standard “within” spatial join. Only use Overpass to dl the data.

If you know a little bit of Python and the idea of downloading a planet file doesn’t put you off, then this sort of thing is really easy (and fast!) in Geodesk:

{
    inner
    for outer in planet("a[amenity=school]")
    for inner in planet("na[amenity=school]").within(outer)
    if inner != outer
}

Though hopefully someone else knows how to do this in Overpass :slight_smile:

Try playing with this example that uses the map_to_area instruction