Search in sources :

Example 1 with JsonFeature

use of com.graphhopper.util.JsonFeature in project graphhopper by graphhopper.

the class PtIsochroneResource method wrap.

private Response wrap(Geometry isoline) {
    JsonFeature feature = new JsonFeature();
    feature.setGeometry(isoline);
    HashMap<String, Object> properties = new HashMap<>();
    properties.put("bucket", 0);
    feature.setProperties(properties);
    Response response = new Response();
    response.polygons.add(feature);
    response.info.copyrights.addAll(ResponsePathSerializer.COPYRIGHTS);
    return response;
}
Also used : JsonFeature(com.graphhopper.util.JsonFeature)

Example 2 with JsonFeature

use of com.graphhopper.util.JsonFeature in project graphhopper by graphhopper.

the class PtIsochroneResource method doGet.

@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response doGet(@QueryParam("point") GHLocationParam sourceParam, @QueryParam("time_limit") @DefaultValue("600") long seconds, @QueryParam("reverse_flow") @DefaultValue("false") boolean reverseFlow, @QueryParam("pt.earliest_departure_time") @NotNull OffsetDateTimeParam departureTimeParam, @QueryParam("pt.blocked_route_types") @DefaultValue("0") int blockedRouteTypes, @QueryParam("result") @DefaultValue("multipolygon") String format) {
    Instant initialTime = departureTimeParam.get().toInstant();
    GHLocation location = sourceParam.get();
    double targetZ = seconds * 1000;
    GeometryFactory geometryFactory = new GeometryFactory();
    final FlagEncoder footEncoder = encodingManager.getEncoder("foot");
    final Weighting weighting = new FastestWeighting(footEncoder);
    DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, graphHopperStorage.getEncodingManager().getBooleanEncodedValue(Subnetwork.key("foot")));
    PtLocationSnapper.Result snapResult = new PtLocationSnapper(graphHopperStorage, locationIndex, gtfsStorage).snapAll(Arrays.asList(location), Arrays.asList(snapFilter));
    GraphExplorer graphExplorer = new GraphExplorer(snapResult.queryGraph, gtfsStorage.getPtGraph(), weighting, gtfsStorage, RealtimeFeed.empty(), reverseFlow, false, false, 5.0, reverseFlow, blockedRouteTypes);
    MultiCriteriaLabelSetting router = new MultiCriteriaLabelSetting(graphExplorer, reverseFlow, false, false, 0, Collections.emptyList());
    Map<Coordinate, Double> z1 = new HashMap<>();
    NodeAccess nodeAccess = snapResult.queryGraph.getNodeAccess();
    for (Label label : router.calcLabels(snapResult.nodes.get(0), initialTime)) {
        if (!((label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1) <= targetZ)) {
            break;
        }
        if (label.node.streetNode != -1) {
            Coordinate nodeCoordinate = new Coordinate(nodeAccess.getLon(label.node.streetNode), nodeAccess.getLat(label.node.streetNode));
            z1.merge(nodeCoordinate, (double) (label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1), Math::min);
        } else if (label.edge != null && (label.edge.getType() == GtfsStorage.EdgeType.EXIT_PT || label.edge.getType() == GtfsStorage.EdgeType.ENTER_PT)) {
            GtfsStorage.PlatformDescriptor platformDescriptor = label.edge.getPlatformDescriptor();
            Stop stop = gtfsStorage.getGtfsFeeds().get(platformDescriptor.feed_id).stops.get(platformDescriptor.stop_id);
            Coordinate nodeCoordinate = new Coordinate(stop.stop_lon, stop.stop_lat);
            z1.merge(nodeCoordinate, (double) (label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1), Math::min);
        }
    }
    if (format.equals("multipoint")) {
        MultiPoint exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0]));
        return wrap(exploredPoints);
    } else {
        MultiPoint exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0]));
        // Get at least all nodes within our bounding box (I think convex hull would be enough.)
        // I think then we should have all possible encroaching points. (Proof needed.)
        locationIndex.query(BBox.fromEnvelope(exploredPoints.getEnvelopeInternal()), edgeId -> {
            EdgeIteratorState edge = snapResult.queryGraph.getEdgeIteratorStateForKey(edgeId * 2);
            z1.merge(new Coordinate(nodeAccess.getLon(edge.getBaseNode()), nodeAccess.getLat(edge.getBaseNode())), Double.MAX_VALUE, Math::min);
            z1.merge(new Coordinate(nodeAccess.getLon(edge.getAdjNode()), nodeAccess.getLat(edge.getAdjNode())), Double.MAX_VALUE, Math::min);
        });
        exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0]));
        CoordinateList siteCoords = DelaunayTriangulationBuilder.extractUniqueCoordinates(exploredPoints);
        List<ConstraintVertex> constraintVertices = new ArrayList<>();
        for (Object siteCoord : siteCoords) {
            Coordinate coord = (Coordinate) siteCoord;
            constraintVertices.add(new ConstraintVertex(coord));
        }
        ConformingDelaunayTriangulator cdt = new ConformingDelaunayTriangulator(constraintVertices, JTS_TOLERANCE);
        cdt.setConstraints(new ArrayList(), new ArrayList());
        cdt.formInitialDelaunay();
        QuadEdgeSubdivision tin = cdt.getSubdivision();
        for (Vertex vertex : (Collection<Vertex>) tin.getVertices(true)) {
            if (tin.isFrameVertex(vertex)) {
                vertex.setZ(Double.MAX_VALUE);
            } else {
                Double aDouble = z1.get(vertex.getCoordinate());
                if (aDouble != null) {
                    vertex.setZ(aDouble);
                } else {
                    vertex.setZ(Double.MAX_VALUE);
                }
            }
        }
        ReadableTriangulation triangulation = ReadableTriangulation.wrap(tin);
        ContourBuilder contourBuilder = new ContourBuilder(triangulation);
        MultiPolygon isoline = contourBuilder.computeIsoline(targetZ, triangulation.getEdges());
        // debugging tool
        if (format.equals("triangulation")) {
            Response response = new Response();
            for (Vertex vertex : (Collection<Vertex>) tin.getVertices(true)) {
                JsonFeature feature = new JsonFeature();
                feature.setGeometry(geometryFactory.createPoint(vertex.getCoordinate()));
                HashMap<String, Object> properties = new HashMap<>();
                properties.put("z", vertex.getZ());
                feature.setProperties(properties);
                response.polygons.add(feature);
            }
            for (QuadEdge edge : (Collection<QuadEdge>) tin.getPrimaryEdges(false)) {
                JsonFeature feature = new JsonFeature();
                feature.setGeometry(edge.toLineSegment().toGeometry(geometryFactory));
                HashMap<String, Object> properties = new HashMap<>();
                feature.setProperties(properties);
                response.polygons.add(feature);
            }
            JsonFeature feature = new JsonFeature();
            feature.setGeometry(isoline);
            HashMap<String, Object> properties = new HashMap<>();
            properties.put("z", targetZ);
            feature.setProperties(properties);
            response.polygons.add(feature);
            response.info.copyrights.addAll(ResponsePathSerializer.COPYRIGHTS);
            return response;
        } else {
            return wrap(isoline);
        }
    }
}
Also used : ConstraintVertex(org.locationtech.jts.triangulate.ConstraintVertex) Vertex(org.locationtech.jts.triangulate.quadedge.Vertex) NodeAccess(com.graphhopper.storage.NodeAccess) FlagEncoder(com.graphhopper.routing.util.FlagEncoder) Stop(com.conveyal.gtfs.model.Stop) ConstraintVertex(org.locationtech.jts.triangulate.ConstraintVertex) EdgeIteratorState(com.graphhopper.util.EdgeIteratorState) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) QuadEdge(org.locationtech.jts.triangulate.quadedge.QuadEdge) DefaultSnapFilter(com.graphhopper.routing.util.DefaultSnapFilter) Instant(java.time.Instant) ReadableTriangulation(com.graphhopper.isochrone.algorithm.ReadableTriangulation) ConformingDelaunayTriangulator(org.locationtech.jts.triangulate.ConformingDelaunayTriangulator) QuadEdgeSubdivision(org.locationtech.jts.triangulate.quadedge.QuadEdgeSubdivision) JsonFeature(com.graphhopper.util.JsonFeature) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Weighting(com.graphhopper.routing.weighting.Weighting) ContourBuilder(com.graphhopper.isochrone.algorithm.ContourBuilder)

Example 3 with JsonFeature

use of com.graphhopper.util.JsonFeature in project graphhopper by graphhopper.

the class JsonFeatureCollectionTest method testDeserialization.

@Test
public void testDeserialization() throws IOException {
    JsonFeatureCollection data = objectMapper.readValue(getClass().getClassLoader().getResourceAsStream("fixtures/geojson1.json"), JsonFeatureCollection.class);
    assertEquals(3, data.getFeatures().size());
    JsonFeature f1 = data.getFeatures().get(0);
    assertEquals("1", f1.getId());
    assertEquals("value0", f1.getProperty("prop0"));
    assertEquals(0.5, f1.getGeometry().getCoordinate().y, .1);
    assertEquals(102.0, f1.getGeometry().getCoordinate().x, .1);
    JsonFeature f2 = data.getFeatures().get(1);
    // read as string despite the 2 (not a string) in json
    assertEquals("2", f2.getId());
    assertEquals(4, f2.getGeometry().getNumPoints());
    assertEquals(0.0, PointList.fromLineString((LineString) f2.getGeometry()).getLat(0), .1);
    assertEquals(102.0, PointList.fromLineString((LineString) f2.getGeometry()).getLon(0), .1);
    assertEquals(1.0, PointList.fromLineString((LineString) f2.getGeometry()).getLat(1), .1);
    assertEquals(103.0, PointList.fromLineString((LineString) f2.getGeometry()).getLon(1), .1);
    JsonFeature f3 = data.getFeatures().get(2);
    assertEquals(0.0, f3.getBBox().getMinY(), 0.0);
    assertEquals(102.0, f3.getBBox().getMinX(), 0.0);
    assertEquals(1.0, f3.getBBox().getMaxY(), 0.0);
    assertEquals(103.0, f3.getBBox().getMaxX(), 0.0);
    assertEquals("a", ((Map) f3.getProperty("prop1")).get("test"));
}
Also used : JsonFeatureCollection(com.graphhopper.util.JsonFeatureCollection) JsonFeature(com.graphhopper.util.JsonFeature) Test(org.junit.jupiter.api.Test)

Example 4 with JsonFeature

use of com.graphhopper.util.JsonFeature in project graphhopper by graphhopper.

the class JsonFeatureCollectionTest method testSerialization.

@Test
public void testSerialization() throws IOException {
    GeometryFactory geometryFactory = new GeometryFactory();
    JsonFeatureCollection jsonFeatureCollection = new JsonFeatureCollection();
    {
        JsonFeature jsonFeature = new JsonFeature();
        jsonFeature.setId("1");
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("prop0", "value0");
        jsonFeature.setProperties(properties);
        jsonFeature.setGeometry(geometryFactory.createPoint(new Coordinate(102.0, 0.5)));
        jsonFeatureCollection.getFeatures().add(jsonFeature);
    }
    {
        JsonFeature jsonFeature = new JsonFeature();
        jsonFeature.setId("2");
        Map<String, Object> properties = new LinkedHashMap<>();
        properties.put("prop0", "value1");
        properties.put("prop1", 2);
        jsonFeature.setProperties(properties);
        jsonFeature.setGeometry(geometryFactory.createLineString(new Coordinate[] { new Coordinate(102.0, 0.0), new Coordinate(103.0, 1.0), new Coordinate(104.0, 0.0), new Coordinate(105.0, 1.0) }));
        jsonFeatureCollection.getFeatures().add(jsonFeature);
    }
    {
        JsonFeature jsonFeature = new JsonFeature();
        jsonFeature.setId("3");
        Map<String, Object> properties = new LinkedHashMap<>();
        properties.put("prop0", "value0");
        Map<String, String> prop1 = new LinkedHashMap<>();
        prop1.put("test", "a");
        properties.put("prop1", prop1);
        jsonFeature.setProperties(properties);
        jsonFeature.setBBox(new Envelope(102.0, 103.0, 0.0, 1));
        jsonFeatureCollection.getFeatures().add(jsonFeature);
    }
    String expected = objectMapper.writeValueAsString(objectMapper.readValue(getClass().getClassLoader().getResourceAsStream("fixtures/geojson1.json"), JsonFeatureCollection.class));
    assertEquals(objectMapper.writeValueAsString(jsonFeatureCollection), expected);
}
Also used : GeometryFactory(org.locationtech.jts.geom.GeometryFactory) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Coordinate(org.locationtech.jts.geom.Coordinate) JsonFeatureCollection(com.graphhopper.util.JsonFeatureCollection) LineString(org.locationtech.jts.geom.LineString) Envelope(org.locationtech.jts.geom.Envelope) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) JsonFeature(com.graphhopper.util.JsonFeature) Test(org.junit.jupiter.api.Test)

Example 5 with JsonFeature

use of com.graphhopper.util.JsonFeature in project graphhopper by graphhopper.

the class CustomModelParserTest method multipleAreas.

@Test
public void multipleAreas() {
    CustomModel customModel = new CustomModel();
    Map<String, JsonFeature> areas = new HashMap<>();
    Coordinate[] area_1_coordinates = new Coordinate[] { new Coordinate(48.019324184801185, 11.28021240234375), new Coordinate(48.019324184801185, 11.53564453125), new Coordinate(48.11843396091691, 11.53564453125), new Coordinate(48.11843396091691, 11.28021240234375), new Coordinate(48.019324184801185, 11.28021240234375) };
    Coordinate[] area_2_coordinates = new Coordinate[] { new Coordinate(48.15509285476017, 11.53289794921875), new Coordinate(48.15509285476017, 11.8212890625), new Coordinate(48.281365151571755, 11.8212890625), new Coordinate(48.281365151571755, 11.53289794921875), new Coordinate(48.15509285476017, 11.53289794921875) };
    areas.put("area_1", new JsonFeature("area_1", "Feature", null, new GeometryFactory().createPolygon(area_1_coordinates), new HashMap<>()));
    areas.put("area_2", new JsonFeature("area_2", "Feature", null, new GeometryFactory().createPolygon(area_2_coordinates), new HashMap<>()));
    customModel.setAreas(areas);
    customModel.addToSpeed(If("in_area_1", LIMIT, 100));
    customModel.addToSpeed(If("!in_area_2", LIMIT, 25));
    customModel.addToSpeed(Else(LIMIT, 15));
    // No exception is thrown during createWeightingParameters
    assertAll(() -> CustomModelParser.createWeightingParameters(customModel, encodingManager, avgSpeedEnc, encoder.getMaxSpeed(), null));
    CustomModel customModel2 = new CustomModel();
    customModel2.setAreas(areas);
    customModel2.addToSpeed(If("in_area_1", LIMIT, 100));
    customModel2.addToSpeed(If("in_area_2", LIMIT, 25));
    customModel2.addToSpeed(If("in_area_3", LIMIT, 150));
    customModel2.addToSpeed(Else(LIMIT, 15));
    assertThrows(IllegalArgumentException.class, () -> CustomModelParser.createWeightingParameters(customModel2, encodingManager, avgSpeedEnc, encoder.getMaxSpeed(), null));
}
Also used : GeometryFactory(org.locationtech.jts.geom.GeometryFactory) HashMap(java.util.HashMap) Coordinate(org.locationtech.jts.geom.Coordinate) CustomModel(com.graphhopper.util.CustomModel) JsonFeature(com.graphhopper.util.JsonFeature) Test(org.junit.jupiter.api.Test)

Aggregations

JsonFeature (com.graphhopper.util.JsonFeature)5 Test (org.junit.jupiter.api.Test)3 JsonFeatureCollection (com.graphhopper.util.JsonFeatureCollection)2 HashMap (java.util.HashMap)2 Coordinate (org.locationtech.jts.geom.Coordinate)2 GeometryFactory (org.locationtech.jts.geom.GeometryFactory)2 Stop (com.conveyal.gtfs.model.Stop)1 ContourBuilder (com.graphhopper.isochrone.algorithm.ContourBuilder)1 ReadableTriangulation (com.graphhopper.isochrone.algorithm.ReadableTriangulation)1 DefaultSnapFilter (com.graphhopper.routing.util.DefaultSnapFilter)1 FlagEncoder (com.graphhopper.routing.util.FlagEncoder)1 FastestWeighting (com.graphhopper.routing.weighting.FastestWeighting)1 Weighting (com.graphhopper.routing.weighting.Weighting)1 NodeAccess (com.graphhopper.storage.NodeAccess)1 CustomModel (com.graphhopper.util.CustomModel)1 EdgeIteratorState (com.graphhopper.util.EdgeIteratorState)1 Instant (java.time.Instant)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 Envelope (org.locationtech.jts.geom.Envelope)1