[GIS] Converting OSM relation to a list of lat/lng points

geojsonopenstreetmap

I would like a convert a relation (e.g. https://openstreetmap.org/relation/2851613) to a list of coordinates that can be displayed on a map, potentially using geojson. I ported over this converter https://wiki.openstreetmap.org/wiki/Relations/Relations_to_GPX (the converted code is at https://github.com/e-mission/e-mission-eval-public-data/blob/master/spec_creation/autofill_eval_spec.py#L71) and it works iff the relations are sane.

However, many relations are malformed. Although the relation spec https://wiki.openstreetmap.org/wiki/Relation says that the members have to be ordered, this relation for the route of bus #52 (https://www.openstreetmap.org/relation/8094017) has the following way order

Way West El Camino Real (516422275) as forward
Way Castro Street (417101895) as forward
Way North El Monte Avenue (52869637) as forward 

which is clearly incorrect since since the 52 goes from Castro to El Monte via El Camino. So if I use the algorithm above, I end up with a map like so

enter image description here

At the same time, OSM displays the route without any zigzags, so it is clearly able to order the relation members correctly even if they are not ordered originally.

In response to @neogeomat, I looked at the nodes displayed by overpass and the nodes displayed by the reconstruction algorithm above for a correctly created relation, and it looks like overpass returns fewer nodes than the algorithm above.
comparing overpass with reconstructed path directly from nodes

Does anybody know how OSM displays relations, or have a pointer to an algorithm that deals gracefully with malformed relations?

Best Answer

You can try osmtogeojson (used by overpass turbo) or one of the alternatives listed at the GeoJSON OSM wiki page. Unfortunately I have no experience with any of them and I'm unsure which one supports sorting of relation members.