public void addNode(OSMNode node) {
      if (!_nodesWithNeighbors.contains(node.getId())) return;

      if (_nodes.containsKey(node.getId())) return;

      _nodes.put(node.getId(), node);

      if (_nodes.size() % 100000 == 0) _log.debug("nodes=" + _nodes.size());
    }
 /**
  * Record the level of the way for this node, e.g. if the way is at level 5, mark that this node
  * is active at level 5.
  *
  * @param the way that has the level
  * @param the node to record for
  * @author mattwigway
  */
 private IntersectionVertex recordLevel(OSMNode node, OSMWay way) {
   HashMap<Integer, IntersectionVertex> levels;
   long nid = node.getId();
   int level = Integer.parseInt(way.getTag("otp:numeric_level"));
   if (multiLevelNodes.containsKey(nid)) {
     levels = multiLevelNodes.get(nid);
   } else {
     levels = new HashMap<Integer, IntersectionVertex>();
     multiLevelNodes.put(nid, levels);
   }
   if (!levels.containsKey(level)) {
     Coordinate coordinate = getCoordinate(node);
     String label = "osm node " + nid;
     IntersectionVertex iv =
         new IntersectionVertex(graph, label, coordinate.x, coordinate.y, label);
     levels.put(level, iv);
     return iv;
   }
   return levels.get(level);
 }
 /**
  * Make or get a shared vertex for flat intersections, or one vertex per level for multilevel
  * nodes like elevators. When there is an elevator or other Z-dimension discontinuity, a single
  * node can appear in several ways at different levels.
  *
  * @param node The node to fetch a label for.
  * @param way The way it is connected to (for fetching level information).
  * @return vertex The graph vertex.
  */
 private IntersectionVertex getVertexForOsmNode(OSMNode node, OSMWay way) {
   // If the node should be decomposed to multiple levels,
   // use the numeric level because it is unique, the human level may not be (although
   // it will likely lead to some head-scratching if it is not).
   IntersectionVertex iv = null;
   if (isMultiLevelNode(node)) {
     // make a separate node for every level
     return recordLevel(node, way);
   }
   // single-level case
   long nid = node.getId();
   iv = intersectionNodes.get(nid);
   if (iv == null) {
     Coordinate coordinate = getCoordinate(node);
     String label = "osm node " + nid;
     iv = new IntersectionVertex(graph, label, coordinate.x, coordinate.y, label);
     intersectionNodes.put(nid, iv);
     endpoints.add(iv);
     // endpoints and intersectionNodes.values are the same thing now right?
   }
   return iv;
 }
 private Coordinate getCoordinate(OSMNode osmNode) {
   return new Coordinate(osmNode.getLon(), osmNode.getLat());
 }
    public void buildGraph(Graph graph) {
      this.graph = graph;

      // handle turn restrictions and road names in relations
      processRelations();

      // Remove all simple islands
      _nodes.keySet().retainAll(_nodesWithNeighbors);

      long wayIndex = 0;

      // store levels that cannot be parsed, and assign them a number
      int nextUnparsedLevel = 0;
      HashMap<String, Integer> unparsedLevels = new HashMap<String, Integer>();

      // figure out which nodes that are actually intersections
      Set<Long> possibleIntersectionNodes = new HashSet<Long>();
      for (OSMWay way : _ways.values()) {
        List<Long> nodes = way.getNodeRefs();
        for (long node : nodes) {
          if (possibleIntersectionNodes.contains(node)) {
            intersectionNodes.put(node, null);
          } else {
            possibleIntersectionNodes.add(node);
          }
        }
      }
      GeometryFactory geometryFactory = new GeometryFactory();

      /* build an ordinary graph, which we will convert to an edge-based graph */

      for (OSMWay way : _ways.values()) {

        if (wayIndex % 10000 == 0) _log.debug("ways=" + wayIndex + "/" + _ways.size());
        wayIndex++;

        WayProperties wayData = wayPropertySet.getDataForWay(way);

        if (!way.hasTag("name")) {
          String creativeName = wayPropertySet.getCreativeNameForWay(way);
          if (creativeName != null) {
            way.addTag("otp:gen_name", creativeName);
          }
        }
        Set<Alert> note = wayPropertySet.getNoteForWay(way);

        StreetTraversalPermission permissions =
            getPermissionsForEntity(way, wayData.getPermission());
        if (permissions == StreetTraversalPermission.NONE) continue;

        List<Long> nodes = way.getNodeRefs();

        IntersectionVertex startEndpoint = null, endEndpoint = null;

        ArrayList<Coordinate> segmentCoordinates = new ArrayList<Coordinate>();

        /* The otp:numeric_level tag adds a constant to level numbers depending on
          where they come from (level map, tags).
          This prevents a layer 1 from being equal to a level_map 1, because they may
          not represent the same thing. Worst case scenario, OTP will say
          "take elevator to level 1" when you're already on level 1.
        */
        final int LEVEL_MAP_LEVEL = 0;
        final int LEVEL_TAG_LEVEL = 100000;
        final int LAYER_TAG_LEVEL = 200000;
        final int OTHER_LEVEL = 300000;
        final int UNPARSED_LEVEL = 400000;

        if (!way.hasTag("otp:numeric_level")) {
          // Parse levels, if a level map was not already applied in processRelations
          String strLevel = null;
          int offset = LEVEL_MAP_LEVEL, intLevel;
          if (way.hasTag("level")) { // TODO: floating-point levels &c.
            strLevel = way.getTag("level");
            offset = LEVEL_TAG_LEVEL;
          } else if (way.hasTag("layer")) {
            strLevel = way.getTag("layer");
            offset = LAYER_TAG_LEVEL;
          }
          if (strLevel != null) {
            try {
              intLevel = Integer.parseInt(strLevel);
            } catch (NumberFormatException e) {
              // could not parse the level string as an integer
              // get a unique level number for this
              if (unparsedLevels.containsKey(strLevel)) {
                intLevel = unparsedLevels.get(strLevel);
              } else { // make a new unique ID
                intLevel = nextUnparsedLevel++;
                unparsedLevels.put(strLevel, intLevel);
              }
              offset = UNPARSED_LEVEL;
              _log.warn(
                  "Could not determine ordinality of layer "
                      + strLevel
                      + ". Elevators will work, but costing may be incorrect. "
                      + "A level map should be used in this situation.");
            }
          } else {
            // no string level description was available. assume ground level, but
            // don't assume it's connected to any other ground level.
            intLevel = 0;
            offset = OTHER_LEVEL;
          }
          if (noZeroLevels && intLevel >= 0) {
            // add 1 to human-readable representation of non-negative levels
            // in (-inf, -1] U [1, inf) locations like the US
            strLevel = Integer.toString(intLevel + 1);
          }
          way.addTag("otp:numeric_level", Integer.toString(intLevel + offset));
          way.addTag("otp:human_level", strLevel); // redunant
          levelHumanNames.put(intLevel + offset, strLevel);
        }

        /*
         * Traverse through all the nodes of this edge. For nodes which are not shared with
         * any other edge, do not create endpoints -- just accumulate them for geometry. For
         * nodes which are shared, create endpoints and StreetVertex instances.
         */
        Long startNode = null;
        OSMNode osmStartNode = null;
        for (int i = 0; i < nodes.size() - 1; i++) {
          Long endNode = nodes.get(i + 1);
          if (osmStartNode == null) {
            startNode = nodes.get(i);
            osmStartNode = _nodes.get(startNode);
          }
          OSMNode osmEndNode = _nodes.get(endNode);

          if (osmStartNode == null || osmEndNode == null) continue;

          LineString geometry;

          /*
           * skip vertices that are not intersections, except that we use them for
           * geometry
           */
          if (segmentCoordinates.size() == 0) {
            segmentCoordinates.add(getCoordinate(osmStartNode));
          }

          if (intersectionNodes.containsKey(endNode) || i == nodes.size() - 2) {
            segmentCoordinates.add(getCoordinate(osmEndNode));
            geometry =
                geometryFactory.createLineString(segmentCoordinates.toArray(new Coordinate[0]));
            segmentCoordinates.clear();
          } else {
            segmentCoordinates.add(getCoordinate(osmEndNode));
            continue;
          }

          /* generate endpoints */
          if (startEndpoint == null) { // first iteration on this way
            // make or get a shared vertex for flat intersections,
            // one vertex per level for multilevel nodes like elevators
            startEndpoint = getVertexForOsmNode(osmStartNode, way);
          } else { // subsequent iterations
            startEndpoint = endEndpoint;
          }

          endEndpoint = getVertexForOsmNode(osmEndNode, way);

          P2<PlainStreetEdge> streets =
              getEdgesForStreet(startEndpoint, endEndpoint, way, i, permissions, geometry);

          PlainStreetEdge street = streets.getFirst();

          if (street != null) {
            double safety = wayData.getSafetyFeatures().getFirst();
            street.setBicycleSafetyEffectiveLength(street.getLength() * safety);
            if (safety < bestBikeSafety) {
              bestBikeSafety = safety;
            }
            if (note != null) {
              street.setNote(note);
            }
          }

          PlainStreetEdge backStreet = streets.getSecond();
          if (backStreet != null) {
            double safety = wayData.getSafetyFeatures().getSecond();
            if (safety < bestBikeSafety) {
              bestBikeSafety = safety;
            }
            backStreet.setBicycleSafetyEffectiveLength(backStreet.getLength() * safety);
            if (note != null) {
              backStreet.setNote(note);
            }
          }

          /* Check if there are turn restrictions starting on this segment */
          List<TurnRestrictionTag> restrictionTags = turnRestrictionsByFromWay.get(way.getId());

          if (restrictionTags != null) {
            for (TurnRestrictionTag tag : restrictionTags) {
              if (tag.via == startNode) {
                TurnRestriction restriction = turnRestrictionsByTag.get(tag);
                restriction.from = backStreet;
              } else if (tag.via == endNode) {
                TurnRestriction restriction = turnRestrictionsByTag.get(tag);
                restriction.from = street;
              }
            }
          }

          restrictionTags = turnRestrictionsByToWay.get(way.getId());
          if (restrictionTags != null) {
            for (TurnRestrictionTag tag : restrictionTags) {
              if (tag.via == startNode) {
                TurnRestriction restriction = turnRestrictionsByTag.get(tag);
                restriction.to = street;
              } else if (tag.via == endNode) {
                TurnRestriction restriction = turnRestrictionsByTag.get(tag);
                restriction.to = backStreet;
              }
            }
          }
          startNode = endNode;
          osmStartNode = _nodes.get(startNode);
        }
      } // END loop over OSM ways

      /* build elevator edges */
      for (Long nodeId : multiLevelNodes.keySet()) {
        OSMNode node = _nodes.get(nodeId);
        // this allows skipping levels, e.g., an elevator that stops
        // at floor 0, 2, 3, and 5.
        // Converting to an Array allows us to
        // subscript it so we can loop over it in twos. Assumedly, it will stay
        // sorted when we convert it to an Array.
        // The objects are Integers, but toArray returns Object[]
        HashMap<Integer, IntersectionVertex> levels = multiLevelNodes.get(nodeId);

        /* first, build FreeEdges to disconnect from the graph,
        GenericVertices to serve as attachment points,
        and ElevatorBoard and ElevatorAlight edges
        to connect future ElevatorHop edges to.
        After this iteration, graph will look like (side view):
        +==+~~X

        +==+~~X

        +==+~~X

        + GenericVertex, X EndpointVertex, ~~ FreeEdge, == ElevatorBoardEdge/ElevatorAlightEdge
        Another loop will fill in the ElevatorHopEdges. */

        ArrayList<Vertex> onboardVertices = new ArrayList<Vertex>();

        Integer[] levelKeys = levels.keySet().toArray(new Integer[0]);
        Arrays.sort(levelKeys);

        for (Integer level : levelKeys) {
          // get the source node to hang all this stuff off of.
          String humanLevel = levelHumanNames.get(level);
          IntersectionVertex sourceVert = levels.get(level);
          String sourceVertLabel = sourceVert.getLabel();

          // create a Vertex to connect the FreeNode to.
          ElevatorOffboardVertex offboardVert =
              new ElevatorOffboardVertex(
                  graph, sourceVertLabel + "_middle", sourceVert.getX(), sourceVert.getY());

          new FreeEdge(sourceVert, offboardVert);
          new FreeEdge(offboardVert, sourceVert);

          // Create a vertex to connect the ElevatorAlight, ElevatorBoard, and
          // ElevatorHop edges to.
          ElevatorOnboardVertex onboardVert =
              new ElevatorOnboardVertex(
                  graph, sourceVertLabel + "_onboard", sourceVert.getX(), sourceVert.getY());

          new ElevatorBoardEdge(offboardVert, onboardVert);
          new ElevatorAlightEdge(onboardVert, offboardVert, humanLevel);

          // add it to the array so it can be connected later
          onboardVertices.add(onboardVert);
        }

        // -1 because we loop over it two at a time
        Integer vSize = onboardVertices.size() - 1;

        for (Integer i = 0; i < vSize; i++) {
          Vertex from = onboardVertices.get(i);
          Vertex to = onboardVertices.get(i + 1);

          StreetTraversalPermission permission = StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE;

          // default to true
          boolean wheelchairAccessible = true;
          // check for bicycle=no, otherwise assume it's OK to take a bike
          if (node.isTagFalse("bicycle")) {
            permission = StreetTraversalPermission.PEDESTRIAN;
          }
          // check for wheelchair=no
          if (node.isTagFalse("wheelchair")) {
            wheelchairAccessible = false;
          }
          // The narrative won't be strictly correct, as it will show the elevator as part
          // of the cycling leg, but I think most cyclists will figure out that they
          // should really dismount.
          ElevatorHopEdge theEdge = new ElevatorHopEdge(from, to, permission);
          ElevatorHopEdge backEdge = new ElevatorHopEdge(to, from, permission);
          theEdge.wheelchairAccessible = wheelchairAccessible;
          backEdge.wheelchairAccessible = wheelchairAccessible;
        }
      } // END elevator edge loop

      /* unify turn restrictions */
      Map<Edge, TurnRestriction> turnRestrictions = new HashMap<Edge, TurnRestriction>();
      for (TurnRestriction restriction : turnRestrictionsByTag.values()) {
        turnRestrictions.put(restriction.from, restriction);
      }
      if (customNamer != null) {
        customNamer.postprocess(graph);
      }
      applyBikeSafetyFactor(graph);
      StreetUtils.pruneFloatingIslands(graph);
      StreetUtils.makeEdgeBased(graph, endpoints, turnRestrictions);
    } // END buildGraph()
 /**
  * Is this a multi-level node that should be decomposed to multiple coincident nodes? Currently
  * returns true only for elevators.
  *
  * @param node
  * @return whether the node is multi-level
  * @author mattwigway
  */
 private boolean isMultiLevelNode(OSMNode node) {
   return node.hasTag("highway") && "elevator".equals(node.getTag("highway"));
 }