Ejemplo n.º 1
0
  @Override
  public void doPost(HttpServletRequest httpReq, HttpServletResponse httpRes)
      throws ServletException, IOException {

    String infoStr =
        httpReq.getRemoteAddr() + " " + httpReq.getLocale() + " " + httpReq.getHeader("User-Agent");
    String type = httpReq.getContentType();
    GPXFile gpxFile;
    if (type.contains("application/xml")) {
      try {
        gpxFile = parseXML(httpReq);
      } catch (Exception ex) {
        logger.warn("Cannot parse XML for " + httpReq.getQueryString() + ", " + infoStr);
        httpRes.setStatus(SC_BAD_REQUEST);
        httpRes.getWriter().append(errorsToXML(Collections.<Throwable>singletonList(ex)));
        return;
      }
    } else {
      throw new IllegalArgumentException("content type not supported " + type);
    }
    final String format = getParam(httpReq, "type", "json");
    boolean writeGPX = GPX_FORMAT.equals(format);
    boolean pointsEncoded = getBooleanParam(httpReq, "points_encoded", true);
    boolean enableInstructions = writeGPX || getBooleanParam(httpReq, "instructions", true);
    boolean enableElevation = getBooleanParam(httpReq, "elevation", false);
    boolean forceRepair = getBooleanParam(httpReq, "force_repair", false);

    // TODO export OSM IDs instead, use https://github.com/karussell/graphhopper-osm-id-mapping
    boolean enableTraversalKeys = getBooleanParam(httpReq, "traversal_keys", false);

    int maxNodesToVisit = (int) getLongParam(httpReq, "max_nodes_to_visit", 500);
    int separatedSearchDistance = (int) getLongParam(httpReq, "separated_search_distance", 300);

    String vehicle = getParam(httpReq, "vehicle", "car");

    Locale locale = Helper.getLocale(getParam(httpReq, "locale", "en"));
    GHResponse matchGHRsp = new GHResponse();
    MatchResult matchRsp = null;
    StopWatch sw = new StopWatch().start();

    try {
      FlagEncoder encoder = hopper.getEncodingManager().getEncoder(vehicle);
      MapMatching matching =
          new MapMatching(hopper.getGraphHopperStorage(), locationIndexMatch, encoder);
      matching.setForceRepair(forceRepair);
      matching.setMaxNodesToVisit(maxNodesToVisit);
      matching.setSeparatedSearchDistance(separatedSearchDistance);

      matchRsp = matching.doWork(gpxFile.getEntries());

      // fill GHResponse for identical structure
      Path path = matching.calcPath(matchRsp);
      Translation tr = trMap.getWithFallBack(locale);
      new PathMerger().doWork(matchGHRsp, Collections.singletonList(path), tr);

    } catch (Exception ex) {
      matchGHRsp.addError(ex);
    }

    logger.info(
        httpReq.getQueryString()
            + ", "
            + infoStr
            + ", took:"
            + sw.stop().getSeconds()
            + ", entries:"
            + gpxFile.getEntries().size()
            + ", "
            + matchGHRsp.getDebugInfo());

    if (EXTENDED_JSON_FORMAT.equals(format)) {
      if (matchGHRsp.hasErrors()) {
        httpRes.setStatus(SC_BAD_REQUEST);
        httpRes.getWriter().append(new JSONArray(matchGHRsp.getErrors()).toString());
      } else {
        httpRes.getWriter().write(new MatchResultToJson(matchRsp).exportTo().toString());
      }

    } else if (GPX_FORMAT.equals(format)) {
      String xml = createGPXString(httpReq, httpRes, matchGHRsp);
      if (matchGHRsp.hasErrors()) {
        httpRes.setStatus(SC_BAD_REQUEST);
        httpRes.getWriter().append(xml);
      } else {
        writeResponse(httpRes, xml);
      }
    } else {
      Map<String, Object> map =
          routeSerializer.toJSON(
              matchGHRsp, true, pointsEncoded, enableElevation, enableInstructions);

      if (matchGHRsp.hasErrors()) {
        writeJsonError(httpRes, SC_BAD_REQUEST, new JSONObject(map));
      } else {

        if (enableTraversalKeys) {
          if (matchRsp == null) {
            throw new IllegalStateException(
                "match response has to be none-null if no error happened");
          }

          // encode edges as traversal keys which includes orientation
          // decode simply by multiplying with 0.5
          List<Integer> traversalKeylist = new ArrayList<Integer>();
          for (EdgeMatch em : matchRsp.getEdgeMatches()) {
            EdgeIteratorState edge = em.getEdgeState();
            traversalKeylist.add(
                GHUtility.createEdgeKey(
                    edge.getBaseNode(), edge.getAdjNode(), edge.getEdge(), false));
          }
          map.put("traversal_keys", traversalKeylist);
        }

        writeJson(httpReq, httpRes, new JSONObject(map));
      }
    }
  }
Ejemplo n.º 2
0
  private void start(CmdArgs args) {
    String action = args.get("action", "").toLowerCase();
    args.put("graph.location", "./graph-cache");
    if (action.equals("import")) {
      String vehicle = args.get("vehicle", "car").toLowerCase();
      args.put("graph.flagEncoders", vehicle);
      args.put("osmreader.osm", args.get("datasource", ""));

      // standard should be to remove disconnected islands
      args.put("prepare.minNetworkSize", 200);
      args.put("prepare.minOneWayNetworkSize", 200);
      GraphHopper hopper = new GraphHopper().init(args);
      hopper.setCHEnable(false);
      hopper.importOrLoad();

    } else if (action.equals("match")) {
      GraphHopper hopper = new GraphHopper().init(args);
      hopper.setCHEnable(false);
      logger.info("loading graph from cache");
      hopper.load("./graph-cache");
      FlagEncoder firstEncoder = hopper.getEncodingManager().fetchEdgeEncoders().get(0);
      GraphHopperStorage graph = hopper.getGraphHopperStorage();

      int gpxAccuracy = args.getInt("gpxAccuracy", 15);
      String instructions = args.get("instructions", "");
      logger.info("Setup lookup index. Accuracy filter is at " + gpxAccuracy + "m");
      LocationIndexMatch locationIndex =
          new LocationIndexMatch(graph, (LocationIndexTree) hopper.getLocationIndex(), gpxAccuracy);
      MapMatching mapMatching = new MapMatching(graph, locationIndex, firstEncoder);
      mapMatching.setSeparatedSearchDistance(args.getInt("separatedSearchDistance", 500));
      mapMatching.setMaxNodesToVisit(args.getInt("maxNodesToVisit", 1000));
      mapMatching.setForceRepair(args.getBool("forceRepair", false));

      // do the actual matching, get the GPX entries from a file or via stream
      String gpxLocation = args.get("gpx", "");
      File[] files = getFiles(gpxLocation);

      logger.info("Now processing " + files.length + " files");
      StopWatch importSW = new StopWatch();
      StopWatch matchSW = new StopWatch();

      Translation tr = new TranslationMap().doImport().get(instructions);

      for (File gpxFile : files) {
        try {
          importSW.start();
          List<GPXEntry> inputGPXEntries =
              new GPXFile().doImport(gpxFile.getAbsolutePath()).getEntries();
          importSW.stop();
          matchSW.start();
          MatchResult mr = mapMatching.doWork(inputGPXEntries);
          matchSW.stop();
          System.out.println(gpxFile);
          System.out.println(
              "\tmatches:\t"
                  + mr.getEdgeMatches().size()
                  + ", gps entries:"
                  + inputGPXEntries.size());
          System.out.println(
              "\tgpx length:\t"
                  + (float) mr.getGpxEntriesLength()
                  + " vs "
                  + (float) mr.getMatchLength());
          System.out.println(
              "\tgpx time:\t"
                  + mr.getGpxEntriesMillis() / 1000f
                  + " vs "
                  + mr.getMatchMillis() / 1000f);

          String outFile = gpxFile.getAbsolutePath() + ".res.gpx";
          System.out.println("\texport results to:" + outFile);

          InstructionList il;
          if (instructions.isEmpty()) {
            il = new InstructionList(null);
          } else {
            AltResponse matchGHRsp = new AltResponse();
            Path path = mapMatching.calcPath(mr);
            new PathMerger().doWork(matchGHRsp, Collections.singletonList(path), tr);
            il = matchGHRsp.getInstructions();
          }

          new GPXFile(mr, il).doExport(outFile);
        } catch (Exception ex) {
          importSW.stop();
          matchSW.stop();
          logger.error("Problem with file " + gpxFile + " Error: " + ex.getMessage());
        }
      }
      System.out.println(
          "gps import took:" + importSW.getSeconds() + "s, match took: " + matchSW.getSeconds());

    } else if (action.equals("getbounds")) {
      String gpxLocation = args.get("gpx", "");
      File[] files = getFiles(gpxLocation);
      BBox bbox = BBox.createInverse(false);
      for (File gpxFile : files) {
        List<GPXEntry> inputGPXEntries =
            new GPXFile().doImport(gpxFile.getAbsolutePath()).getEntries();
        for (GPXEntry entry : inputGPXEntries) {
          if (entry.getLat() < bbox.minLat) {
            bbox.minLat = entry.getLat();
          }
          if (entry.getLat() > bbox.maxLat) {
            bbox.maxLat = entry.getLat();
          }
          if (entry.getLon() < bbox.minLon) {
            bbox.minLon = entry.getLon();
          }
          if (entry.getLon() > bbox.maxLon) {
            bbox.maxLon = entry.getLon();
          }
        }
      }

      System.out.println("max bounds: " + bbox);

      // show download only for small areas
      if (bbox.maxLat - bbox.minLat < 0.1 && bbox.maxLon - bbox.minLon < 0.1) {
        double delta = 0.01;
        System.out.println(
            "Get small areas via\n"
                + "wget -O extract.osm 'http://overpass-api.de/api/map?bbox="
                + (bbox.minLon - delta)
                + ","
                + (bbox.minLat - delta)
                + ","
                + (bbox.maxLon + delta)
                + ","
                + (bbox.maxLat + delta)
                + "'");
      }
    } else {
      System.out.println(
          "Usage: Do an import once, then do the matching\n"
              + "./map-matching action=import datasource=your.pbf\n"
              + "./map-matching action=match gpx=your.gpx\n"
              + "./map-matching action=match gpx=.*gpx\n\n"
              + "Or start in-built matching web service\n"
              + "./map-matching action=start-server\n\n");
    }
  }