Search in sources :

Example 51 with GHPoint

use of com.graphhopper.util.shapes.GHPoint in project graphhopper by graphhopper.

the class GraphHopperServlet method doGet.

@Override
public void doGet(HttpServletRequest httpReq, HttpServletResponse httpRes) throws ServletException, IOException {
    List<GHPoint> requestPoints = getPoints(httpReq, "point");
    GHResponse ghRsp = new GHResponse();
    double minPathPrecision = getDoubleParam(httpReq, WAY_POINT_MAX_DISTANCE, 1d);
    boolean writeGPX = "gpx".equalsIgnoreCase(getParam(httpReq, "type", "json"));
    boolean enableInstructions = writeGPX || getBooleanParam(httpReq, INSTRUCTIONS, true);
    boolean calcPoints = getBooleanParam(httpReq, CALC_POINTS, true);
    boolean enableElevation = getBooleanParam(httpReq, "elevation", false);
    boolean pointsEncoded = getBooleanParam(httpReq, "points_encoded", true);
    String vehicleStr = getParam(httpReq, "vehicle", "car");
    String weighting = getParam(httpReq, "weighting", "fastest");
    String algoStr = getParam(httpReq, "algorithm", "");
    String localeStr = getParam(httpReq, "locale", "en");
    StopWatch sw = new StopWatch().start();
    if (!ghRsp.hasErrors()) {
        try {
            List<Double> favoredHeadings = Collections.EMPTY_LIST;
            try {
                favoredHeadings = getDoubleParamList(httpReq, "heading");
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("heading list in wrong format: " + e.getMessage());
            }
            if (!hopper.getEncodingManager().supports(vehicleStr)) {
                throw new IllegalArgumentException("Vehicle not supported: " + vehicleStr);
            } else if (enableElevation && !hopper.hasElevation()) {
                throw new IllegalArgumentException("Elevation not supported!");
            } else if (favoredHeadings.size() > 1 && favoredHeadings.size() != requestPoints.size()) {
                throw new IllegalArgumentException("The number of 'heading' parameters must be <= 1 " + "or equal to the number of points (" + requestPoints.size() + ")");
            }
            List<String> pointHints = new ArrayList<String>(Arrays.asList(getParams(httpReq, POINT_HINT)));
            if (pointHints.size() > 0 && pointHints.size() != requestPoints.size()) {
                throw new IllegalArgumentException("If you pass " + POINT_HINT + ", you need to pass a hint for every point, empty hints will be ignored");
            }
            FlagEncoder algoVehicle = hopper.getEncodingManager().getEncoder(vehicleStr);
            GHRequest request;
            if (favoredHeadings.size() > 0) {
                // if only one favored heading is specified take as start heading
                if (favoredHeadings.size() == 1) {
                    List<Double> paddedHeadings = new ArrayList<Double>(Collections.nCopies(requestPoints.size(), Double.NaN));
                    paddedHeadings.set(0, favoredHeadings.get(0));
                    request = new GHRequest(requestPoints, paddedHeadings);
                } else {
                    request = new GHRequest(requestPoints, favoredHeadings);
                }
            } else {
                request = new GHRequest(requestPoints);
            }
            initHints(request.getHints(), httpReq.getParameterMap());
            request.setVehicle(algoVehicle.toString()).setWeighting(weighting).setAlgorithm(algoStr).setLocale(localeStr).setPointHints(pointHints).getHints().put(CALC_POINTS, calcPoints).put(INSTRUCTIONS, enableInstructions).put(WAY_POINT_MAX_DISTANCE, minPathPrecision);
            ghRsp = hopper.route(request);
        } catch (IllegalArgumentException ex) {
            ghRsp.addError(ex);
        }
    }
    float took = sw.stop().getSeconds();
    String infoStr = httpReq.getRemoteAddr() + " " + httpReq.getLocale() + " " + httpReq.getHeader("User-Agent");
    String logStr = httpReq.getQueryString() + " " + infoStr + " " + requestPoints + ", took:" + took + ", " + algoStr + ", " + weighting + ", " + vehicleStr;
    httpRes.setHeader("X-GH-Took", "" + Math.round(took * 1000));
    int alternatives = ghRsp.getAll().size();
    if (writeGPX && alternatives > 1)
        ghRsp.addError(new IllegalArgumentException("Alternatives are currently not yet supported for GPX"));
    if (ghRsp.hasErrors()) {
        logger.error(logStr + ", errors:" + ghRsp.getErrors());
    } else {
        PathWrapper altRsp0 = ghRsp.getBest();
        logger.info(logStr + ", alternatives: " + alternatives + ", distance0: " + altRsp0.getDistance() + ", time0: " + Math.round(altRsp0.getTime() / 60000f) + "min" + ", points0: " + altRsp0.getPoints().getSize() + ", debugInfo: " + ghRsp.getDebugInfo());
    }
    if (writeGPX) {
        if (ghRsp.hasErrors()) {
            httpRes.setStatus(SC_BAD_REQUEST);
            httpRes.getWriter().append(errorsToXML(ghRsp.getErrors()));
        } else {
            // no error => we can now safely call getFirst
            String xml = createGPXString(httpReq, httpRes, ghRsp.getBest());
            writeResponse(httpRes, xml);
        }
    } else {
        Map<String, Object> map = routeSerializer.toJSON(ghRsp, calcPoints, pointsEncoded, enableElevation, enableInstructions);
        Object infoMap = map.get("info");
        if (infoMap != null)
            ((Map) infoMap).put("took", Math.round(took * 1000));
        if (ghRsp.hasErrors())
            writeJsonError(httpRes, SC_BAD_REQUEST, new JSONObject(map));
        else {
            writeJson(httpReq, httpRes, new JSONObject(map));
        }
    }
}
Also used : FlagEncoder(com.graphhopper.routing.util.FlagEncoder) GHResponse(com.graphhopper.GHResponse) GHPoint(com.graphhopper.util.shapes.GHPoint) StopWatch(com.graphhopper.util.StopWatch) PathWrapper(com.graphhopper.PathWrapper) JSONObject(org.json.JSONObject) GHRequest(com.graphhopper.GHRequest) JSONObject(org.json.JSONObject) GHPoint(com.graphhopper.util.shapes.GHPoint)

Example 52 with GHPoint

use of com.graphhopper.util.shapes.GHPoint in project graphhopper by graphhopper.

the class GraphHopperWeb method route.

@Override
public GHResponse route(GHRequest request) {
    try {
        String places = "";
        for (GHPoint p : request.getPoints()) {
            places += "point=" + p.lat + "," + p.lon + "&";
        }
        boolean tmpInstructions = request.getHints().getBool("instructions", instructions);
        boolean tmpCalcPoints = request.getHints().getBool("calc_points", calcPoints);
        boolean tmpTurnDescription = request.getHints().getBool("turn_description", turnDescription);
        if (tmpInstructions && !tmpCalcPoints)
            throw new IllegalStateException("Cannot calculate instructions without points (only points without instructions). " + "Use calc_points=false and instructions=false to disable point and instruction calculation");
        boolean tmpElevation = request.getHints().getBool("elevation", elevation);
        String url = routeServiceUrl + "?" + places + "&type=json" + "&instructions=" + tmpInstructions + "&points_encoded=true" + "&calc_points=" + tmpCalcPoints + "&algorithm=" + request.getAlgorithm() + "&locale=" + request.getLocale().toString() + "&elevation=" + tmpElevation;
        if (!request.getVehicle().isEmpty())
            url += "&vehicle=" + request.getVehicle();
        if (!key.isEmpty())
            url += "&key=" + key;
        for (Entry<String, String> entry : request.getHints().toMap().entrySet()) {
            String urlKey = entry.getKey();
            String urlValue = entry.getValue();
            // use lower case conversion for check only!
            if (ignoreSet.contains(urlKey.toLowerCase()))
                continue;
            if (urlValue != null && !urlValue.isEmpty())
                url += "&" + WebHelper.encodeURL(urlKey) + "=" + WebHelper.encodeURL(urlValue);
        }
        String str = downloader.downloadAsString(url, true);
        JSONObject json = new JSONObject(str);
        GHResponse res = new GHResponse();
        res.addErrors(readErrors(json));
        if (res.hasErrors())
            return res;
        JSONArray paths = json.getJSONArray("paths");
        for (int index = 0; index < paths.length(); index++) {
            JSONObject path = paths.getJSONObject(index);
            PathWrapper altRsp = createPathWrapper(path, tmpCalcPoints, tmpInstructions, tmpElevation, tmpTurnDescription);
            res.add(altRsp);
        }
        return res;
    } catch (Exception ex) {
        throw new RuntimeException("Problem while fetching path " + request.getPoints() + ": " + ex.getMessage(), ex);
    }
}
Also used : DetailedRuntimeException(com.graphhopper.util.exceptions.DetailedRuntimeException) JSONObject(org.json.JSONObject) PathWrapper(com.graphhopper.PathWrapper) JSONArray(org.json.JSONArray) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse) GHPoint(com.graphhopper.util.shapes.GHPoint) DetailedRuntimeException(com.graphhopper.util.exceptions.DetailedRuntimeException) PointOutOfBoundsException(com.graphhopper.util.exceptions.PointOutOfBoundsException) PointNotFoundException(com.graphhopper.util.exceptions.PointNotFoundException) DetailedIllegalArgumentException(com.graphhopper.util.exceptions.DetailedIllegalArgumentException) JSONException(org.json.JSONException) ConnectionNotFoundException(com.graphhopper.util.exceptions.ConnectionNotFoundException)

Example 53 with GHPoint

use of com.graphhopper.util.shapes.GHPoint in project graphhopper by graphhopper.

the class NearestServlet method doGet.

@Override
public void doGet(HttpServletRequest httpReq, HttpServletResponse httpRes) throws ServletException, IOException {
    String pointStr = getParam(httpReq, "point", null);
    boolean enabledElevation = getBooleanParam(httpReq, "elevation", false);
    JSONObject result = new JSONObject();
    if (pointStr != null && !pointStr.equalsIgnoreCase("")) {
        GHPoint place = GHPoint.parse(pointStr);
        LocationIndex index = hopper.getLocationIndex();
        QueryResult qr = index.findClosest(place.lat, place.lon, EdgeFilter.ALL_EDGES);
        if (!qr.isValid()) {
            result.put("error", "Nearest point cannot be found!");
        } else {
            GHPoint3D snappedPoint = qr.getSnappedPoint();
            result.put("type", "Point");
            JSONArray coord = new JSONArray();
            coord.put(snappedPoint.lon);
            coord.put(snappedPoint.lat);
            if (hopper.hasElevation() && enabledElevation)
                coord.put(snappedPoint.ele);
            result.put("coordinates", coord);
            // Distance from input to snapped point in meters
            result.put("distance", calc.calcDist(place.lat, place.lon, snappedPoint.lat, snappedPoint.lon));
        }
    } else {
        result.put("error", "No lat/lon specified!");
    }
    writeJson(httpReq, httpRes, result);
}
Also used : QueryResult(com.graphhopper.storage.index.QueryResult) JSONObject(org.json.JSONObject) GHPoint3D(com.graphhopper.util.shapes.GHPoint3D) JSONArray(org.json.JSONArray) GHPoint(com.graphhopper.util.shapes.GHPoint) LocationIndex(com.graphhopper.storage.index.LocationIndex)

Example 54 with GHPoint

use of com.graphhopper.util.shapes.GHPoint in project graphhopper by graphhopper.

the class GraphHopperOSMTest method testGetPathsDirectionEnforcement2.

@Test
public void testGetPathsDirectionEnforcement2() {
    // Test enforce south start direction and east end direction
    instance = createSquareGraphInstance(false);
    // Start in middle of edge 4-5 
    GHPoint start = new GHPoint(0.0015, 0.002);
    // End at middle of edge 2-3
    GHPoint end = new GHPoint(0.002, 0.0005);
    GHRequest req = new GHRequest().addPoint(start, 180.).addPoint(end, 90.);
    GHResponse response = new GHResponse();
    List<Path> paths = instance.calcPaths(req, response);
    assertFalse(response.hasErrors());
    assertArrayEquals(new int[] { 9, 5, 8, 1, 2, 10 }, paths.get(0).calcNodes().toArray());
    // Test uni-directional case
    req.setAlgorithm(DIJKSTRA);
    response = new GHResponse();
    paths = instance.calcPaths(req, response);
    assertFalse(response.hasErrors());
    assertArrayEquals(new int[] { 9, 5, 8, 1, 2, 10 }, paths.get(0).calcNodes().toArray());
}
Also used : GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse) Test(org.junit.Test)

Example 55 with GHPoint

use of com.graphhopper.util.shapes.GHPoint in project graphhopper by graphhopper.

the class GraphHopperOSMTest method testGetPathsDirectionEnforcement1.

@Test
public void testGetPathsDirectionEnforcement1() {
    // Test enforce start direction
    // Note: This Test does not pass for CH enabled    
    instance = createSquareGraphInstance(false);
    // Start in middle of edge 4-5 
    GHPoint start = new GHPoint(0.0015, 0.002);
    // End at middle of edge 2-3
    GHPoint end = new GHPoint(0.002, 0.0005);
    GHRequest req = new GHRequest().addPoint(start, 180.).addPoint(end);
    GHResponse response = new GHResponse();
    List<Path> paths = instance.calcPaths(req, response);
    assertFalse(response.hasErrors());
    assertArrayEquals(new int[] { 9, 5, 8, 3, 10 }, paths.get(0).calcNodes().toArray());
}
Also used : GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse) Test(org.junit.Test)

Aggregations

GHPoint (com.graphhopper.util.shapes.GHPoint)69 Test (org.junit.Test)34 QueryResult (com.graphhopper.storage.index.QueryResult)15 GHRequest (com.graphhopper.GHRequest)10 GHResponse (com.graphhopper.GHResponse)10 PathWrapper (com.graphhopper.PathWrapper)6 DistanceCalcEarth (com.graphhopper.util.DistanceCalcEarth)5 PointList (com.graphhopper.util.PointList)3 PointNotFoundException (com.graphhopper.util.exceptions.PointNotFoundException)3 BBox (com.graphhopper.util.shapes.BBox)3 GHPoint3D (com.graphhopper.util.shapes.GHPoint3D)3 Random (java.util.Random)3 JSONObject (org.json.JSONObject)3 IntArrayList (com.carrotsearch.hppc.IntArrayList)2 ReaderWay (com.graphhopper.reader.ReaderWay)2 EdgeFilter (com.graphhopper.routing.util.EdgeFilter)2 SpatialRule (com.graphhopper.routing.util.spatialrules.SpatialRule)2 Graph (com.graphhopper.storage.Graph)2 VLongStorage (com.graphhopper.storage.VLongStorage)2 PointDistanceExceededException (com.graphhopper.util.exceptions.PointDistanceExceededException)2