Search in sources :

Example 81 with LineString

use of org.locationtech.jts.geom.LineString in project series-rest-api by 52North.

the class GeoJSONDecoder method decodeMultiLineString.

protected MultiLineString decodeMultiLineString(JsonNode node, GeometryFactory fac) throws GeoJSONException {
    JsonNode coordinates = requireCoordinates(node);
    LineString[] lineStrings = new LineString[coordinates.size()];
    for (int i = 0; i < coordinates.size(); ++i) {
        JsonNode coords = coordinates.get(i);
        lineStrings[i] = fac.createLineString(decodeCoordinates(coords));
    }
    return fac.createMultiLineString(lineStrings);
}
Also used : MultiLineString(org.locationtech.jts.geom.MultiLineString) LineString(org.locationtech.jts.geom.LineString) JsonNode(com.fasterxml.jackson.databind.JsonNode) Point(org.locationtech.jts.geom.Point) MultiPoint(org.locationtech.jts.geom.MultiPoint)

Example 82 with LineString

use of org.locationtech.jts.geom.LineString in project series-rest-api by 52North.

the class GeoJSONTest method randomLineString.

private LineString randomLineString(int srid) {
    LineString geometry = geometryFactory.createLineString(new Coordinate[] { randomCoordinate(), randomCoordinate(), randomCoordinate() });
    geometry.setSRID(srid);
    return geometry;
}
Also used : MultiLineString(org.locationtech.jts.geom.MultiLineString) LineString(org.locationtech.jts.geom.LineString)

Example 83 with LineString

use of org.locationtech.jts.geom.LineString in project graphhopper by graphhopper.

the class ResponsePathDeserializer method deserializePointList.

private static PointList deserializePointList(ObjectMapper objectMapper, JsonNode jsonNode, boolean hasElevation) {
    PointList snappedPoints;
    if (jsonNode.isTextual()) {
        snappedPoints = decodePolyline(jsonNode.asText(), Math.max(10, jsonNode.asText().length() / 4), hasElevation);
    } else {
        LineString lineString = objectMapper.convertValue(jsonNode, LineString.class);
        snappedPoints = PointList.fromLineString(lineString);
    }
    return snappedPoints;
}
Also used : LineString(org.locationtech.jts.geom.LineString)

Example 84 with LineString

use of org.locationtech.jts.geom.LineString 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 85 with LineString

use of org.locationtech.jts.geom.LineString in project graphhopper by graphhopper.

the class MapMatchingResourceTest method testBike.

@Test
public void testBike() throws ParseException {
    WKTReader wktReader = new WKTReader();
    final Response response = app.client().target("http://localhost:8080/match?profile=fast_bike").request().buildPost(Entity.xml(getClass().getResourceAsStream("another-tour-with-loop.gpx"))).invoke();
    assertEquals(200, response.getStatus(), "no success");
    JsonNode json = response.readEntity(JsonNode.class);
    JsonNode path = json.get("paths").get(0);
    LineString expectedGeometry = (LineString) wktReader.read("LINESTRING (12.3607 51.34365, 12.36418 51.34443, 12.36379 51.34538, 12.36082 51.34471, 12.36188 51.34278)");
    LineString actualGeometry = ResponsePathDeserializer.decodePolyline(path.get("points").asText(), 10, false).toLineString(false);
    assertEquals(DiscreteHausdorffDistance.distance(expectedGeometry, actualGeometry), 0.0, 1E-4);
    // ensure that is actually also is bike! (slower than car)
    assertEquals(162, path.get("time").asLong() / 1000f, 1);
}
Also used : Response(javax.ws.rs.core.Response) LineString(org.locationtech.jts.geom.LineString) JsonNode(com.fasterxml.jackson.databind.JsonNode) WKTReader(org.locationtech.jts.io.WKTReader) Test(org.junit.jupiter.api.Test)

Aggregations

LineString (org.locationtech.jts.geom.LineString)120 MultiLineString (org.locationtech.jts.geom.MultiLineString)48 Coordinate (org.locationtech.jts.geom.Coordinate)38 Geometry (org.locationtech.jts.geom.Geometry)35 Point (org.locationtech.jts.geom.Point)32 Test (org.junit.Test)24 Polygon (org.locationtech.jts.geom.Polygon)21 MultiPoint (org.locationtech.jts.geom.MultiPoint)19 GeometryFactory (org.locationtech.jts.geom.GeometryFactory)14 WKTReader (org.locationtech.jts.io.WKTReader)13 ArrayList (java.util.ArrayList)12 CustomCoordinateSequence (org.apache.jena.geosparql.implementation.jts.CustomCoordinateSequence)12 HashMap (java.util.HashMap)10 DimensionInfo (org.apache.jena.geosparql.implementation.DimensionInfo)9 GeometryWrapper (org.apache.jena.geosparql.implementation.GeometryWrapper)9 ParseException (org.locationtech.jts.io.ParseException)9 DefaultGeometryProperty (eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty)8 GeometryNotSupportedException (eu.esdihumboldt.hale.io.gml.geometry.GeometryNotSupportedException)7 MultiPolygon (org.locationtech.jts.geom.MultiPolygon)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)6