Search in sources :

Example 51 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project spatial-portal by AtlasOfLivingAustralia.

the class MapComposer method warnForLargeWKT.

public void warnForLargeWKT(MapLayer ml) {
    //display warning for large wkt that does not have a facet
    if (ml.getFacets() == null) {
        WKTReader wktReader = new WKTReader();
        try {
            Geometry g = wktReader.read(ml.getWKT());
            if (g.getNumPoints() > Integer.parseInt(CommonData.getSettings().getProperty("max_q_wkt_points", "200"))) {
                WKTReducedDTO reduced = Util.reduceWKT(ml.getWKT());
                ml.setWKT(reduced.getReducedWKT());
                Geometry gsimplified = wktReader.read(ml.getWKT());
                getMapComposer().showMessage("WARNING: The polygon has more than the maximum number of points and has been simplified, " + "\r\n\r\noriginal points: " + g.getNumPoints() + "\r\nmax points: " + CommonData.getSettings().getProperty("max_q_wkt_points", "200") + "\r\nsimplified points: " + gsimplified.getNumPoints());
            }
        } catch (Exception e) {
            LOGGER.error("error testing and reducing WKT", e);
        }
    }
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) WKTReader(com.vividsolutions.jts.io.WKTReader) WKTReducedDTO(au.org.ala.spatial.dto.WKTReducedDTO) ParseException(org.json.simple.parser.ParseException)

Example 52 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project graphhopper by graphhopper.

the class TripFromLabel method parsePathIntoLegs.

// We are parsing a string of edges into a hierarchical trip.
// One could argue that one should never write a parser
// by hand, because it is always ugly, but use a parser library.
// The code would then read like a specification of what paths through the graph mean.
private List<Trip.Leg> parsePathIntoLegs(List<Label.Transition> path, GraphExplorer graph, Weighting weighting, Translation tr) {
    if (path.size() <= 1) {
        return Collections.emptyList();
    }
    if (GtfsStorage.EdgeType.ENTER_PT == path.get(1).edge.edgeType) {
        final GtfsStorage.FeedIdWithTimezone feedIdWithTimezone = gtfsStorage.getTimeZones().get(path.get(1).edge.timeZoneId);
        List<Trip.Leg> result = new ArrayList<>();
        long boardTime = -1;
        List<Label.Transition> partition = null;
        for (int i = 1; i < path.size(); i++) {
            Label.Transition transition = path.get(i);
            Label.EdgeLabel edge = path.get(i).edge;
            if (edge.edgeType == GtfsStorage.EdgeType.BOARD) {
                boardTime = transition.label.currentTime;
                partition = new ArrayList<>();
            }
            if (partition != null) {
                partition.add(path.get(i));
            }
            if (EnumSet.of(GtfsStorage.EdgeType.TRANSFER, GtfsStorage.EdgeType.LEAVE_TIME_EXPANDED_NETWORK).contains(edge.edgeType)) {
                Geometry lineString = lineStringFromEdges(partition);
                GtfsRealtime.TripDescriptor tripDescriptor;
                try {
                    tripDescriptor = GtfsRealtime.TripDescriptor.parseFrom(realtimeFeed.getTripDescriptor(partition.get(0).edge.edgeIteratorState.getEdge()));
                } catch (InvalidProtocolBufferException e) {
                    throw new RuntimeException(e);
                }
                final StopsFromBoardHopDwellEdges stopsFromBoardHopDwellEdges = new StopsFromBoardHopDwellEdges(feedIdWithTimezone.feedId, tripDescriptor);
                partition.stream().filter(e -> EnumSet.of(GtfsStorage.EdgeType.HOP, GtfsStorage.EdgeType.BOARD, GtfsStorage.EdgeType.DWELL).contains(e.edge.edgeType)).forEach(stopsFromBoardHopDwellEdges::next);
                stopsFromBoardHopDwellEdges.finish();
                List<Trip.Stop> stops = stopsFromBoardHopDwellEdges.stops;
                result.add(new Trip.PtLeg(feedIdWithTimezone.feedId, partition.get(0).edge.nTransfers == 0, tripDescriptor.getTripId(), tripDescriptor.getRouteId(), edges(partition).map(edgeLabel -> edgeLabel.edgeIteratorState).collect(Collectors.toList()), stops, partition.stream().mapToDouble(t -> t.edge.distance).sum(), path.get(i - 1).label.currentTime - boardTime, lineString));
                partition = null;
            }
        }
        return result;
    } else {
        InstructionList instructions = new InstructionList(tr);
        InstructionsFromEdges instructionsFromEdges = new InstructionsFromEdges(path.get(1).edge.edgeIteratorState.getBaseNode(), graph.getGraph(), weighting, weighting.getFlagEncoder(), graph.getNodeAccess(), tr, instructions);
        int prevEdgeId = -1;
        for (int i = 1; i < path.size(); i++) {
            EdgeIteratorState edge = path.get(i).edge.edgeIteratorState;
            instructionsFromEdges.next(edge, i, prevEdgeId);
            prevEdgeId = edge.getEdge();
        }
        instructionsFromEdges.finish();
        final Instant departureTime = Instant.ofEpochMilli(path.get(0).label.currentTime);
        final Instant arrivalTime = Instant.ofEpochMilli(path.get(path.size() - 1).label.currentTime);
        return Collections.singletonList(new Trip.WalkLeg("Walk", Date.from(departureTime), edges(path).map(edgeLabel -> edgeLabel.edgeIteratorState).collect(Collectors.toList()), lineStringFromEdges(path), edges(path).mapToDouble(edgeLabel -> edgeLabel.distance).sum(), instructions, Date.from(arrivalTime)));
    }
}
Also used : java.util(java.util) Stop(com.conveyal.gtfs.model.Stop) LoggerFactory(org.slf4j.LoggerFactory) LocalDateTime(java.time.LocalDateTime) InstructionsFromEdges(com.graphhopper.routing.InstructionsFromEdges) Duration(java.time.Duration) Geometry(com.vividsolutions.jts.geom.Geometry) Fares(com.graphhopper.gtfs.fare.Fares) StreamSupport(java.util.stream.StreamSupport) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) GtfsRealtime(com.google.transit.realtime.GtfsRealtime) Coordinate(com.vividsolutions.jts.geom.Coordinate) SECONDS(java.time.temporal.ChronoUnit.SECONDS) com.graphhopper.util(com.graphhopper.util) Logger(org.slf4j.Logger) GTFSFeed(com.conveyal.gtfs.GTFSFeed) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Label.reverseEdges(com.graphhopper.reader.gtfs.Label.reverseEdges) Fun(org.mapdb.Fun) Stream(java.util.stream.Stream) StopTime(com.conveyal.gtfs.model.StopTime) PathWrapper(com.graphhopper.PathWrapper) Weighting(com.graphhopper.routing.weighting.Weighting) Trip(com.graphhopper.Trip) GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) InstructionsFromEdges(com.graphhopper.routing.InstructionsFromEdges) Stop(com.conveyal.gtfs.model.Stop) Trip(com.graphhopper.Trip) Instant(java.time.Instant) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) GtfsRealtime(com.google.transit.realtime.GtfsRealtime) Geometry(com.vividsolutions.jts.geom.Geometry)

Example 53 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project graphhopper by graphhopper.

the class SpatialRuleLookupBuilder method buildIndex.

/**
 * Builds a SpatialRuleLookup by passing the provided JSON features into the provided
 * SpatialRuleFactory and collecting all the SpatialRule instances that it returns,
 * ignoring when it returns SpatialRule.EMPTY.
 * <p>
 * See {@link SpatialRuleLookup} and {@link SpatialRule}.
 *
 * @param jsonFeatureCollection a feature collection
 * @param jsonIdField           the name of a property in that feature collection which serves as an id
 * @param spatialRuleFactory    a factory which is called with all the (id, geometry) pairs.
 *                              It should provide a SpatialRule for each id it knows about,
 *                              and SpatialRule.EMPTY otherwise.
 * @param maxBBox               limit the maximum BBox of the SpatialRuleLookup to the given BBox
 * @return the fully constructed SpatialRuleLookup.
 */
public static SpatialRuleLookup buildIndex(JsonFeatureCollection jsonFeatureCollection, String jsonIdField, SpatialRuleFactory spatialRuleFactory, double resolution, BBox maxBBox) {
    BBox polygonBounds = BBox.createInverse(false);
    List<SpatialRule> spatialRules = new ArrayList<>();
    for (int jsonFeatureIdx = 0; jsonFeatureIdx < jsonFeatureCollection.getFeatures().size(); jsonFeatureIdx++) {
        JsonFeature jsonFeature = jsonFeatureCollection.getFeatures().get(jsonFeatureIdx);
        String id = jsonIdField.isEmpty() || toLowerCase(jsonIdField).equals("id") ? jsonFeature.getId() : (String) jsonFeature.getProperty(jsonIdField);
        if (id == null || id.isEmpty())
            throw new IllegalArgumentException("ID cannot be empty but was for JsonFeature " + jsonFeatureIdx);
        List<Polygon> borders = new ArrayList<>();
        for (int i = 0; i < jsonFeature.getGeometry().getNumGeometries(); i++) {
            Geometry poly = jsonFeature.getGeometry().getGeometryN(i);
            if (poly instanceof com.vividsolutions.jts.geom.Polygon)
                borders.add(Polygon.create((com.vividsolutions.jts.geom.Polygon) poly));
            else
                throw new IllegalArgumentException("Geometry for " + id + " (" + i + ") not supported " + poly.getClass().getSimpleName());
        }
        SpatialRule spatialRule = spatialRuleFactory.createSpatialRule(id, borders);
        if (spatialRule != SpatialRule.EMPTY) {
            spatialRules.add(spatialRule);
            for (Polygon polygon : spatialRule.getBorders()) {
                polygonBounds.update(polygon.getMinLat(), polygon.getMinLon());
                polygonBounds.update(polygon.getMaxLat(), polygon.getMaxLon());
            }
        }
    }
    if (!polygonBounds.isValid()) {
        return SpatialRuleLookup.EMPTY;
    }
    BBox calculatedBounds = polygonBounds.calculateIntersection(maxBBox);
    if (calculatedBounds == null)
        return SpatialRuleLookup.EMPTY;
    SpatialRuleLookup spatialRuleLookup = new SpatialRuleLookupArray(spatialRules, resolution, true, calculatedBounds);
    logger.info("Created the SpatialRuleLookup with the following rules: " + Arrays.toString(spatialRules.toArray()));
    return spatialRuleLookup;
}
Also used : ArrayList(java.util.ArrayList) JsonFeature(com.graphhopper.json.geo.JsonFeature) Geometry(com.vividsolutions.jts.geom.Geometry) BBox(com.graphhopper.util.shapes.BBox)

Example 54 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project elasticsearch by elastic.

the class LineStringBuilder method build.

@Override
public Shape build() {
    Coordinate[] coordinates = this.coordinates.toArray(new Coordinate[this.coordinates.size()]);
    Geometry geometry;
    if (wrapdateline) {
        ArrayList<LineString> strings = decompose(FACTORY, coordinates, new ArrayList<LineString>());
        if (strings.size() == 1) {
            geometry = strings.get(0);
        } else {
            LineString[] linestrings = strings.toArray(new LineString[strings.size()]);
            geometry = FACTORY.createMultiLineString(linestrings);
        }
    } else {
        geometry = FACTORY.createLineString(coordinates);
    }
    return jtsGeometry(geometry);
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) Coordinate(com.vividsolutions.jts.geom.Coordinate) LineString(com.vividsolutions.jts.geom.LineString)

Example 55 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project elasticsearch by elastic.

the class MultiLineStringBuilder method build.

@Override
public Shape build() {
    final Geometry geometry;
    if (wrapdateline) {
        ArrayList<LineString> parts = new ArrayList<>();
        for (LineStringBuilder line : lines) {
            LineStringBuilder.decompose(FACTORY, line.coordinates(false), parts);
        }
        if (parts.size() == 1) {
            geometry = parts.get(0);
        } else {
            LineString[] lineStrings = parts.toArray(new LineString[parts.size()]);
            geometry = FACTORY.createMultiLineString(lineStrings);
        }
    } else {
        LineString[] lineStrings = new LineString[lines.size()];
        Iterator<LineStringBuilder> iterator = lines.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            lineStrings[i] = FACTORY.createLineString(iterator.next().coordinates(false));
        }
        geometry = FACTORY.createMultiLineString(lineStrings);
    }
    return jtsGeometry(geometry);
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) LineString(com.vividsolutions.jts.geom.LineString) ArrayList(java.util.ArrayList)

Aggregations

Geometry (com.vividsolutions.jts.geom.Geometry)125 WKTReader (com.vividsolutions.jts.io.WKTReader)35 Test (org.junit.Test)31 Coordinate (com.vividsolutions.jts.geom.Coordinate)24 Point (com.vividsolutions.jts.geom.Point)21 ParseException (com.vividsolutions.jts.io.ParseException)19 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)14 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)14 Envelope (com.vividsolutions.jts.geom.Envelope)13 WKTWriter (com.vividsolutions.jts.io.WKTWriter)13 ArrayList (java.util.ArrayList)13 LineString (com.vividsolutions.jts.geom.LineString)10 MultiPoint (com.vividsolutions.jts.geom.MultiPoint)9 Metacard (ddf.catalog.data.Metacard)9 SimpleFeature (org.opengis.feature.simple.SimpleFeature)7 Optional (com.google.common.base.Optional)6 IOException (java.io.IOException)6 RevFeature (org.locationtech.geogig.api.RevFeature)6 JtsGeometry (org.locationtech.spatial4j.shape.jts.JtsGeometry)6 GeometryCollection (com.vividsolutions.jts.geom.GeometryCollection)5