Search in sources :

Example 86 with GraphHopper

use of com.graphhopper.GraphHopper in project graphhopper by graphhopper.

the class RoutingAlgorithmWithOSMTest method testMoscow.

@Test
public void testMoscow() {
    // extracted from OSM area: "37.582641,55.805261,37.626929,55.824455"
    List<Query> queries = new ArrayList<>();
    // choose perpendicular
    // http://localhost:8989/?point=55.818994%2C37.595354&point=55.819175%2C37.596931
    queries.add(new Query(55.818891, 37.59515, 55.81997, 37.59854, 1052, 14));
    // should choose the closest road not the other one (opposite direction)
    // http://localhost:8989/?point=55.818898%2C37.59661&point=55.819066%2C37.596374
    queries.add(new Query(55.818536, 37.595848, 55.818702, 37.595564, 24, 2));
    // respect one way!
    // http://localhost:8989/?point=55.819066%2C37.596374&point=55.818898%2C37.59661
    queries.add(new Query(55.818702, 37.595564, 55.818536, 37.595848, 1114, 23));
    GraphHopper hopper = createHopper(MOSCOW, new Profile("car").setVehicle("car").setWeighting("fastest"));
    hopper.setMinNetworkSize(200);
    hopper.importOrLoad();
    checkQueries(hopper, queries);
}
Also used : ArrayList(java.util.ArrayList) GraphHopper(com.graphhopper.GraphHopper) Profile(com.graphhopper.config.Profile) CHProfile(com.graphhopper.config.CHProfile) LMProfile(com.graphhopper.config.LMProfile) Test(org.junit.jupiter.api.Test)

Example 87 with GraphHopper

use of com.graphhopper.GraphHopper in project graphhopper by graphhopper.

the class MapMatching2Test method testIssue127.

@Test
public void testIssue127() throws IOException {
    GraphHopper hopper = new GraphHopper();
    hopper.setOSMFile("../map-matching/files/map-issue13.osm.gz");
    hopper.setGraphHopperLocation(GH_LOCATION);
    hopper.setProfiles(new Profile("my_profile").setVehicle("car").setWeighting("fastest"));
    hopper.getLMPreparationHandler().setLMProfiles(new LMProfile("my_profile"));
    hopper.importOrLoad();
    MapMatching mapMatching = new MapMatching(hopper, new PMap().putObject("profile", "my_profile"));
    // query with two identical points
    Gpx gpx = xmlMapper.readValue(getClass().getResourceAsStream("/issue-127.gpx"), Gpx.class);
    MatchResult mr = mapMatching.match(GpxConversions.getEntries(gpx.trk.get(0)));
    // make sure no virtual edges are returned
    int edgeCount = hopper.getGraphHopperStorage().getAllEdges().length();
    for (EdgeMatch em : mr.getEdgeMatches()) {
        assertTrue(em.getEdgeState().getEdge() < edgeCount, "result contains virtual edges:" + em.getEdgeState().toString());
        validateEdgeMatch(em);
    }
    assertEquals(0, mr.getMatchMillis(), 50);
}
Also used : MapMatching(com.graphhopper.matching.MapMatching) EdgeMatch(com.graphhopper.matching.EdgeMatch) PMap(com.graphhopper.util.PMap) LMProfile(com.graphhopper.config.LMProfile) GraphHopper(com.graphhopper.GraphHopper) MatchResult(com.graphhopper.matching.MatchResult) Profile(com.graphhopper.config.Profile) LMProfile(com.graphhopper.config.LMProfile) Gpx(com.graphhopper.jackson.Gpx) Test(org.junit.jupiter.api.Test)

Example 88 with GraphHopper

use of com.graphhopper.GraphHopper in project graphhopper by graphhopper.

the class MVTResource method doGetXyz.

@GET
@Path("{z}/{x}/{y}.mvt")
@Produces("application/x-protobuf")
public Response doGetXyz(@Context HttpServletRequest httpReq, @Context UriInfo uriInfo, @PathParam("z") int zInfo, @PathParam("x") int xInfo, @PathParam("y") int yInfo, @QueryParam(Parameters.Details.PATH_DETAILS) List<String> pathDetails) {
    if (zInfo <= 9) {
        VectorTile.Tile.Builder mvtBuilder = VectorTile.Tile.newBuilder();
        return Response.fromResponse(Response.ok(mvtBuilder.build().toByteArray(), PBF).build()).header("X-GH-Took", "0").build();
    }
    StopWatch totalSW = new StopWatch().start();
    Coordinate nw = num2deg(xInfo, yInfo, zInfo);
    Coordinate se = num2deg(xInfo + 1, yInfo + 1, zInfo);
    LocationIndexTree locationIndex = (LocationIndexTree) graphHopper.getLocationIndex();
    final NodeAccess na = graphHopper.getGraphHopperStorage().getNodeAccess();
    BBox bbox = new BBox(nw.x, se.x, se.y, nw.y);
    if (!bbox.isValid())
        throw new IllegalStateException("Invalid bbox " + bbox);
    final GeometryFactory geometryFactory = new GeometryFactory();
    VectorTile.Tile.Builder mvtBuilder = VectorTile.Tile.newBuilder();
    final IGeometryFilter acceptAllGeomFilter = geometry -> true;
    final Envelope tileEnvelope = new Envelope(se, nw);
    final MvtLayerParams layerParams = new MvtLayerParams(256, 4096);
    final UserDataKeyValueMapConverter converter = new UserDataKeyValueMapConverter();
    if (!encodingManager.hasEncodedValue(RoadClass.KEY))
        throw new IllegalStateException("You need to configure GraphHopper to store road_class, e.g. graph.encoded_values: road_class,max_speed,... ");
    final EnumEncodedValue<RoadClass> roadClassEnc = encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class);
    final AtomicInteger edgeCounter = new AtomicInteger(0);
    // in toFeatures addTags of the converter is called and layerProps is filled with keys&values => those need to be stored in the layerBuilder
    // otherwise the decoding won't be successful and "undefined":"undefined" instead of "speed": 30 is the result
    final MvtLayerProps layerProps = new MvtLayerProps();
    final VectorTile.Tile.Layer.Builder layerBuilder = MvtLayerBuild.newLayerBuilder("roads", layerParams);
    locationIndex.query(bbox, edgeId -> {
        EdgeIteratorState edge = graphHopper.getGraphHopperStorage().getEdgeIteratorStateForKey(edgeId * 2);
        LineString lineString;
        RoadClass rc = edge.get(roadClassEnc);
        if (zInfo >= 14) {
            PointList pl = edge.fetchWayGeometry(FetchMode.ALL);
            lineString = pl.toLineString(false);
        } else if (rc == RoadClass.MOTORWAY || zInfo > 10 && (rc == RoadClass.PRIMARY || rc == RoadClass.TRUNK) || zInfo > 11 && (rc == RoadClass.SECONDARY) || zInfo > 12) {
            double lat = na.getLat(edge.getBaseNode());
            double lon = na.getLon(edge.getBaseNode());
            double toLat = na.getLat(edge.getAdjNode());
            double toLon = na.getLon(edge.getAdjNode());
            lineString = geometryFactory.createLineString(new Coordinate[] { new Coordinate(lon, lat), new Coordinate(toLon, toLat) });
        } else {
            // skip edge for certain zoom
            return;
        }
        edgeCounter.incrementAndGet();
        Map<String, Object> map = new HashMap<>(2);
        map.put("name", edge.getName());
        for (String str : pathDetails) {
            // how to indicate an erroneous parameter?
            if (str.contains(",") || !encodingManager.hasEncodedValue(str))
                continue;
            EncodedValue ev = encodingManager.getEncodedValue(str, EncodedValue.class);
            if (ev instanceof EnumEncodedValue)
                map.put(ev.getName(), edge.get((EnumEncodedValue) ev).toString());
            else if (ev instanceof DecimalEncodedValue)
                map.put(ev.getName(), edge.get((DecimalEncodedValue) ev));
            else if (ev instanceof BooleanEncodedValue)
                map.put(ev.getName(), edge.get((BooleanEncodedValue) ev));
            else if (ev instanceof IntEncodedValue)
                map.put(ev.getName(), edge.get((IntEncodedValue) ev));
        }
        lineString.setUserData(map);
        // doing some AffineTransformation
        TileGeomResult tileGeom = JtsAdapter.createTileGeom(lineString, tileEnvelope, geometryFactory, layerParams, acceptAllGeomFilter);
        List<VectorTile.Tile.Feature> features = JtsAdapter.toFeatures(tileGeom.mvtGeoms, layerProps, converter);
        layerBuilder.addAllFeatures(features);
    });
    MvtLayerBuild.writeProps(layerBuilder, layerProps);
    mvtBuilder.addLayers(layerBuilder.build());
    byte[] bytes = mvtBuilder.build().toByteArray();
    totalSW.stop();
    logger.debug("took: " + totalSW.getSeconds() + ", edges:" + edgeCounter.get());
    return Response.ok(bytes, PBF).header("X-GH-Took", "" + totalSW.getSeconds() * 1000).build();
}
Also used : com.graphhopper.routing.ev(com.graphhopper.routing.ev) IGeometryFilter(com.wdtinc.mapbox_vector_tile.adapt.jts.IGeometryFilter) JtsAdapter(com.wdtinc.mapbox_vector_tile.adapt.jts.JtsAdapter) LoggerFactory(org.slf4j.LoggerFactory) VectorTile(com.wdtinc.mapbox_vector_tile.VectorTile) Coordinate(org.locationtech.jts.geom.Coordinate) HashMap(java.util.HashMap) MvtLayerBuild(com.wdtinc.mapbox_vector_tile.build.MvtLayerBuild) MvtLayerParams(com.wdtinc.mapbox_vector_tile.build.MvtLayerParams) EncodingManager(com.graphhopper.routing.util.EncodingManager) Inject(javax.inject.Inject) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) GraphHopper(com.graphhopper.GraphHopper) com.graphhopper.util(com.graphhopper.util) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) Logger(org.slf4j.Logger) Context(javax.ws.rs.core.Context) BBox(com.graphhopper.util.shapes.BBox) UserDataKeyValueMapConverter(com.wdtinc.mapbox_vector_tile.adapt.jts.UserDataKeyValueMapConverter) TileGeomResult(com.wdtinc.mapbox_vector_tile.adapt.jts.TileGeomResult) LineString(org.locationtech.jts.geom.LineString) List(java.util.List) NodeAccess(com.graphhopper.storage.NodeAccess) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) MvtLayerProps(com.wdtinc.mapbox_vector_tile.build.MvtLayerProps) UriInfo(javax.ws.rs.core.UriInfo) Envelope(org.locationtech.jts.geom.Envelope) NodeAccess(com.graphhopper.storage.NodeAccess) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) HashMap(java.util.HashMap) LineString(org.locationtech.jts.geom.LineString) Envelope(org.locationtech.jts.geom.Envelope) TileGeomResult(com.wdtinc.mapbox_vector_tile.adapt.jts.TileGeomResult) UserDataKeyValueMapConverter(com.wdtinc.mapbox_vector_tile.adapt.jts.UserDataKeyValueMapConverter) MvtLayerProps(com.wdtinc.mapbox_vector_tile.build.MvtLayerProps) VectorTile(com.wdtinc.mapbox_vector_tile.VectorTile) IGeometryFilter(com.wdtinc.mapbox_vector_tile.adapt.jts.IGeometryFilter) VectorTile(com.wdtinc.mapbox_vector_tile.VectorTile) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) Coordinate(org.locationtech.jts.geom.Coordinate) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) LineString(org.locationtech.jts.geom.LineString) BBox(com.graphhopper.util.shapes.BBox) MvtLayerParams(com.wdtinc.mapbox_vector_tile.build.MvtLayerParams)

Example 89 with GraphHopper

use of com.graphhopper.GraphHopper in project graphhopper by graphhopper.

the class OSMReaderTest method testNegativeIds.

@Test
public void testNegativeIds() {
    String fileNegIds = "test-osm-negative-ids.xml";
    GraphHopper hopper = new GraphHopperFacade(fileNegIds).importOrLoad();
    Graph graph = hopper.getGraphHopperStorage();
    assertEquals(4, graph.getNodes());
    int n20 = AbstractGraphStorageTester.getIdOf(graph, 52);
    int n10 = AbstractGraphStorageTester.getIdOf(graph, 51.2492152);
    int n30 = AbstractGraphStorageTester.getIdOf(graph, 51.2);
    assertEquals(GHUtility.asSet(n20), GHUtility.getNeighbors(carOutExplorer.setBaseNode(n10)));
    assertEquals(3, GHUtility.count(carOutExplorer.setBaseNode(n20)));
    assertEquals(GHUtility.asSet(n20), GHUtility.getNeighbors(carOutExplorer.setBaseNode(n30)));
    EdgeIterator iter = carOutExplorer.setBaseNode(n20);
    assertTrue(iter.next());
    assertTrue(iter.next());
    assertEquals(n30, iter.getAdjNode());
    assertEquals(93147, iter.getDistance(), 1);
    assertTrue(iter.next());
    assertEquals(n10, iter.getAdjNode());
    assertEquals(88643, iter.getDistance(), 1);
}
Also used : GraphHopper(com.graphhopper.GraphHopper) Test(org.junit.jupiter.api.Test) GraphHopperTest(com.graphhopper.GraphHopperTest)

Example 90 with GraphHopper

use of com.graphhopper.GraphHopper in project graphhopper by graphhopper.

the class OSMReaderTest method testTurnFlagCombination.

/**
 * Tests the combination of different turn cost flags by different encoders.
 */
@Test
public void testTurnFlagCombination() {
    CarFlagEncoder car = new CarFlagEncoder(5, 5, 24);
    CarFlagEncoder truck = new CarFlagEncoder(5, 5, 24) {

        @Override
        public TransportationMode getTransportationMode() {
            return TransportationMode.HGV;
        }

        @Override
        public String getName() {
            return "truck";
        }
    };
    BikeFlagEncoder bike = new BikeFlagEncoder(4, 2, 24, false);
    GraphHopper hopper = new GraphHopper();
    hopper.getEncodingManagerBuilder().add(bike).add(truck).add(car);
    hopper.setOSMFile(getClass().getResource("test-multi-profile-turn-restrictions.xml").getFile()).setGraphHopperLocation(dir).setProfiles(new Profile("bike").setVehicle("bike").setWeighting("fastest"), new Profile("car").setVehicle("car").setWeighting("fastest"), new Profile("truck").setVehicle("truck").setWeighting("fastest")).importOrLoad();
    EncodingManager manager = hopper.getEncodingManager();
    DecimalEncodedValue carTCEnc = manager.getDecimalEncodedValue(TurnCost.key("car"));
    DecimalEncodedValue truckTCEnc = manager.getDecimalEncodedValue(TurnCost.key("truck"));
    DecimalEncodedValue bikeTCEnc = manager.getDecimalEncodedValue(TurnCost.key("bike"));
    Graph graph = hopper.getGraphHopperStorage();
    TurnCostStorage tcStorage = graph.getTurnCostStorage();
    int edge1 = GHUtility.getEdge(graph, 1, 0).getEdge();
    int edge2 = GHUtility.getEdge(graph, 0, 2).getEdge();
    // the 2nd entry provides turn flags for bike only
    assertTrue(Double.isInfinite(tcStorage.get(carTCEnc, edge1, 0, edge2)));
    assertTrue(Double.isInfinite(tcStorage.get(truckTCEnc, edge1, 0, edge2)));
    assertEquals(0, tcStorage.get(bikeTCEnc, edge1, 0, edge2), .1);
    edge1 = GHUtility.getEdge(graph, 2, 0).getEdge();
    edge2 = GHUtility.getEdge(graph, 0, 3).getEdge();
    // the first entry provides turn flags for car and foot only
    assertEquals(0, tcStorage.get(carTCEnc, edge1, 0, edge2), .1);
    assertEquals(0, tcStorage.get(truckTCEnc, edge1, 0, edge2), .1);
    assertTrue(Double.isInfinite(tcStorage.get(bikeTCEnc, edge1, 0, edge2)));
    edge1 = GHUtility.getEdge(graph, 3, 0).getEdge();
    edge2 = GHUtility.getEdge(graph, 0, 2).getEdge();
    assertEquals(0, tcStorage.get(carTCEnc, edge1, 0, edge2), .1);
    assertTrue(Double.isInfinite(tcStorage.get(truckTCEnc, edge1, 0, edge2)));
    assertEquals(0, tcStorage.get(bikeTCEnc, edge1, 0, edge2), .1);
}
Also used : GraphHopper(com.graphhopper.GraphHopper) Profile(com.graphhopper.config.Profile) Test(org.junit.jupiter.api.Test) GraphHopperTest(com.graphhopper.GraphHopperTest)

Aggregations

GraphHopper (com.graphhopper.GraphHopper)101 Test (org.junit.jupiter.api.Test)62 Profile (com.graphhopper.config.Profile)52 LMProfile (com.graphhopper.config.LMProfile)44 CHProfile (com.graphhopper.config.CHProfile)39 GraphHopperTest (com.graphhopper.GraphHopperTest)25 ArrayList (java.util.ArrayList)24 File (java.io.File)16 Test (org.junit.Test)11 SRTMProvider (com.graphhopper.reader.dem.SRTMProvider)10 GHRequest (com.graphhopper.GHRequest)7 GHResponse (com.graphhopper.GHResponse)7 GraphHopperConfig (com.graphhopper.GraphHopperConfig)6 GraphHopperOSM (com.graphhopper.reader.osm.GraphHopperOSM)6 EncodingManager (com.graphhopper.routing.util.EncodingManager)6 PMap (com.graphhopper.util.PMap)6 GHPoint (com.graphhopper.util.shapes.GHPoint)5 IOException (java.io.IOException)5 Gpx (com.graphhopper.jackson.Gpx)4 MapMatching (com.graphhopper.matching.MapMatching)4