Java 类com.vividsolutions.jts.geom.Point 实例源码

项目:sumo    文件:JTSUtil.java   
/** */
public static Geometry flatten (GeometryCollection gc) {
    final List<Point> points = new LinkedList<Point>();
    final List<LineString> lines = new LinkedList<LineString>();
    final List<Polygon> polygons = new LinkedList<Polygon>();
    gc.apply(new GeometryFilter() {
            public void filter (Geometry geom) {
                if (geom instanceof Point) {
                    points.add((Point)geom);
                } else if (geom instanceof LineString) {
                    lines.add((LineString)geom);
                } else if (geom instanceof Polygon) {
                    polygons.add((Polygon)geom);
                }
            }
        });
    if (!polygons.isEmpty()) {
        return gc.getFactory().createMultiPolygon(GeometryFactory.toPolygonArray(polygons));
    } else if (!lines.isEmpty()) {
        return gc.getFactory().createMultiLineString(GeometryFactory.toLineStringArray(lines));
    } else {
        return gc.getFactory().createMultiPoint(GeometryFactory.toPointArray(points));
    }
}
项目:openrouteservice    文件:JsonLocationsRequestParser.java   
private static void checkSearchRadius(Geometry geom, double value) throws Exception
{
    if (geom instanceof Point)
    {
        if (LocationsServiceSettings.getMaximumSearchRadiusForPoints() > 0 && LocationsServiceSettings.getMaximumSearchRadiusForPoints() < value)
            throw new ParameterOutOfRangeException(LocationsErrorCodes.PARAMETER_VALUE_EXCEEDS_MAXIMUM, "radius", Double.toString(value), Double.toString(LocationsServiceSettings.getMaximumSearchRadiusForPoints()));
    }
    else if (geom instanceof LineString)
    {
        if (LocationsServiceSettings.getMaximumSearchRadiusForLinestrings() > 0 && LocationsServiceSettings.getMaximumSearchRadiusForLinestrings() < value)
            throw new ParameterOutOfRangeException(LocationsErrorCodes.PARAMETER_VALUE_EXCEEDS_MAXIMUM, "radius", Double.toString(value), Double.toString(LocationsServiceSettings.getMaximumSearchRadiusForLinestrings()));
    }
    else if (geom instanceof Polygon)
    {
        if (LocationsServiceSettings.getMaximumSearchRadiusForPolygons() > 0 && LocationsServiceSettings.getMaximumSearchRadiusForPolygons() < value)
            throw new ParameterOutOfRangeException(LocationsErrorCodes.PARAMETER_VALUE_EXCEEDS_MAXIMUM, "radius", Double.toString(value), Double.toString(LocationsServiceSettings.getMaximumSearchRadiusForPolygons()));
    }
}
项目:synthea_java    文件:Hospital.java   
public static Hospital findClosestInpatient(Point personLocation) {
  double personLat = personLocation.getY();
  double personLong = personLocation.getX();

  double closestDistance = Double.MAX_VALUE;
  Provider closestHospital = null;
  for (Provider p : Provider.getServices().get(Provider.INPATIENT)) {
    Point hospitalLocation = p.getCoordinates();
    double hospitalLat = hospitalLocation.getY();
    double hospitalLong = hospitalLocation.getX();
    double sphericalDistance = haversine(personLat, personLong, hospitalLat, hospitalLong);
    if (sphericalDistance < closestDistance) {
      closestDistance = sphericalDistance;
      closestHospital = p;
    }
  }
  return (Hospital) closestHospital;
}
项目:synthea_java    文件:Hospital.java   
public static Hospital findClosestEmergency(Point personLocation) {
  double personLat = personLocation.getY();
  double personLong = personLocation.getX();

  double closestDistance = Double.MAX_VALUE;
  Provider closestHospital = null;
  for (Provider p : Provider.getServices().get(Provider.EMERGENCY)) {
    Point hospitalLocation = p.getCoordinates();
    double hospitalLat = hospitalLocation.getY();
    double hospitalLong = hospitalLocation.getX();
    double sphericalDistance = haversine(personLat, personLong, hospitalLat, hospitalLong);
    if (sphericalDistance < closestDistance) {
      closestDistance = sphericalDistance;
      closestHospital = p;
    }
  }
  return (Hospital) closestHospital;
}
项目:sumo    文件:FactoryLayer.java   
/**
 *
 * @param type
 * @param layer
 * @param parent
 * @return
 */
public static GenericLayer createComplexLayer(GeometryImage layer) {

    ComplexEditVDSVectorLayer clayer = null;
    Geometry frame = layer.getGeometries().get(0);
    if (!(frame instanceof Point)) {
        layer.remove(frame);
        List<Geometry> frames = new ArrayList<Geometry>();
        frames.add(frame);

        clayer = new ComplexEditVDSVectorLayer(LayerManager.getIstanceManager().getCurrentImageLayer(),
                layer.getName(), layer.getGeometryType(), layer);

        clayer.addGeometries("image frame", Color.BLUE, 1, GeometryImage.LINESTRING, frames, false);

    } else {
        clayer = new ComplexEditVDSVectorLayer(LayerManager.getIstanceManager().getCurrentImageLayer(),
                layer.getName(), layer.getGeometryType(), layer);

    }
    return clayer;
}
项目:sumo    文件:MaskVectorLayer.java   
/**
 *
 * @param imagePosition
 * @param context
 */
public void mouseClicked(java.awt.Point imagePosition, OpenGLContext context) {
    if(isEditable()){
     this.selectedGeometry = null;
     GeometryFactory gf = new GeometryFactory();
     com.vividsolutions.jts.geom.Point p = gf.createPoint(new Coordinate(imagePosition.x, imagePosition.y));
     for (Geometry temp : glayer.getGeometries()) {
        if(temp instanceof Polygon){
        Coordinate[] c=DistanceOp.nearestPoints(temp, p);
        com.vividsolutions.jts.geom.Point nearest=gf.createPoint(c[0]);
          if (nearest.isWithinDistance(temp,5 * context.getZoom())) {
              this.selectedGeometry = temp;
              System.out.println(""+temp.getCoordinate().x+","+temp.getCoordinate().y);
              LayerPickedData.put(temp, glayer.getAttributes(temp));
              break;
          }
        }
     }
    }
}
项目:openrouteservice    文件:GeometryJSON.java   
public static JSONArray toJSON(Geometry geom, StringBuffer buffer) throws Exception
{
    if (geom instanceof Polygon)
    {
        return toJSON((Polygon)geom);
    }
    else if (geom instanceof LineString)
    {
        return toJSON((LineString)geom, false);
    }
    else if (geom instanceof Point)
    {
        return toJSON((Point)geom);
    }
    else if (geom instanceof MultiPolygon)
    {
        return toJSON((MultiPolygon)geom);
    }
    else 
    {
        throw new Exception("toJSON function is not implemented for " + geom.getGeometryType());
    }
}
项目:elasticsearch_my    文件:GeoJSONShapeParserTests.java   
public void testThatParserExtractsCorrectTypeAndCoordinatesFromArbitraryJson() throws IOException {
    XContentBuilder pointGeoJson = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("crs")
                    .field("type", "name")
                    .startObject("properties")
                        .field("name", "urn:ogc:def:crs:OGC:1.3:CRS84")
                    .endObject()
                .endObject()
                .field("bbox", "foobar")
                .field("type", "point")
                .field("bubu", "foobar")
                .startArray("coordinates").value(100.0).value(0.0).endArray()
                .startObject("nested").startArray("coordinates").value(200.0).value(0.0).endArray().endObject()
                .startObject("lala").field("type", "NotAPoint").endObject()
            .endObject();

    Point expected = GEOMETRY_FACTORY.createPoint(new Coordinate(100.0, 0.0));
    assertGeometryEquals(new JtsPoint(expected, SPATIAL_CONTEXT), pointGeoJson);
}
项目:graphium    文件:TestWayGraphReadDaoImpl.java   
@Test
@Transactional(readOnly=true)
public void testFindNearestSegments() {
    String viewName = "gip_at_frc_0_4";
    String version = "16_02_160229";
    Point referencePoint = GeometryUtils.createPoint2D(13.04378, 47.80464, 4326);
    float radiusInKm = 0.2f;
    int maxNrOfSegments = 10;
    List<IWaySegment> segments = null;
    try {
        segments = dao.findNearestSegments(viewName, version, referencePoint, radiusInKm, maxNrOfSegments);
    } catch (GraphNotExistsException e) {
        log.error("",e);
    }
    Assert.assertNotNull(segments);
    Long[] expectedSegmentIds = new Long[] {901418172L, 901418173L, 901413319L, 901411604L, 901413318L, 901456931L, 901411391L, 901456932L, 901410749L, 901415156L};
    int i = 0;
    for (IWaySegment segment : segments) {
        log.info("" + segment.getId());
        Assert.assertEquals(expectedSegmentIds[i++], (Long)segment.getId());
    }
}
项目:fpm    文件:BoundariesA0ShapefileTest.java   
@BeforeClass
public static void setup() {

    TomtomFolder tomtomFolder = mock(TomtomFolder.class);
    when(tomtomFolder.getFile("___a0.shp")).thenReturn("src/test/resources/tomtom/boundaries/a0/andorra______________a0.shp");

    CapitalProvider capitalProvider = mock(CapitalProvider.class);
    Point point = new Point(new PackedCoordinateSequence.Double(new double[]{1.52185, 42.50760}, 2), new GeometryFactory());
    Centroid capital = new Centroid(10560000718742L, "Capital Name", "123", 0, 1, 7, point);
    when(capitalProvider.get(0)).thenReturn(newArrayList(capital));

    NameProvider nameProvider = mock(NameProvider.class);
    when(nameProvider.getAlternateNames(10200000000008L)).thenReturn(of("name", "Andorra", "name:fr", "Andorre"));

    OsmLevelGenerator osmLevelGenerator = mock(OsmLevelGenerator.class);
    when(osmLevelGenerator.getOsmLevel("andorra", 0)).thenReturn("2");

    BoundariesA0Shapefile shapefile = new BoundariesA0Shapefile(tomtomFolder, capitalProvider, nameProvider, osmLevelGenerator);

    shapefile.serialize("target/tests/");

    pbfContent = read(new File("target/tests/a0.osm.pbf"));
}
项目:fpm    文件:BoundariesA2ShapefileTest.java   
@BeforeClass
public static void setup() {

    TomtomFolder tomtomFolder = mock(TomtomFolder.class);
    when(tomtomFolder.getFile("___a2.shp")).thenReturn("src/test/resources/tomtom/boundaries/a2/belbe2___________a2.shp");

    NameProvider nameProvider = mock(NameProvider.class);
    when(nameProvider.getAlternateNames(10560000000838L)).thenReturn(of("name", "Leuven"));

    OsmLevelGenerator osmLevelGenerator = mock(OsmLevelGenerator.class);
    when(osmLevelGenerator.getOsmLevel("belbe2", 2)).thenReturn("6");

    CapitalProvider capitalProvider = mock(CapitalProvider.class);
    Point point = new Point(new PackedCoordinateSequence.Double(new double[]{4.703077, 50.8756041}, 2), new GeometryFactory());
    Centroid capital = new Centroid(10560000718742L, "Capital Name", "123", 2, 1, 7, point);
    when(capitalProvider.get(2)).thenReturn(newArrayList(capital));

    BoundariesA2Shapefile shapefile = new BoundariesA2Shapefile(tomtomFolder, capitalProvider, nameProvider, osmLevelGenerator);

    shapefile.serialize("target/tests/");

    pbfContent = read(new File("target/tests/a2.osm.pbf"));
}
项目:fpm    文件:BoundariesA1ShapefileTest.java   
@BeforeClass
public static void setup() {

    TomtomFolder tomtomFolder = mock(TomtomFolder.class);
    when(tomtomFolder.getFile("___a1.shp")).thenReturn("src/test/resources/tomtom/boundaries/a1/belgium______________a1.shp");

    NameProvider nameProvider = mock(NameProvider.class);
    when(nameProvider.getAlternateNames(10560000000843L)).thenReturn(of("name", "Brussel", "name:fr", "Bruxelles"));

    OsmLevelGenerator osmLevelGenerator = mock(OsmLevelGenerator.class);
    when(osmLevelGenerator.getOsmLevel("belgium", 1)).thenReturn("4");

    CapitalProvider capitalProvider = mock(CapitalProvider.class);
    Point point = new Point(new PackedCoordinateSequence.Double(new double[]{4.868077, 50.4536041}, 2), new GeometryFactory());
    Centroid capital = new Centroid(10560000718742L, "Capital Name", "123", 1, 1, 7, point);
    when(capitalProvider.get(1)).thenReturn(newArrayList(capital));

    BoundariesA1Shapefile shapefile = new BoundariesA1Shapefile(tomtomFolder, capitalProvider, nameProvider, osmLevelGenerator);

    shapefile.serialize("target/tests/");

    pbfContent = read(new File("target/tests/a1.osm.pbf"));
}
项目:xsharing-services-router    文件:ConverterUtil.java   
public static BikeStation toBikeStation(MBPlaceEntity mbPlaceEntity, List<VehicleStatus> vehicleStatusList) {
    if (mbPlaceEntity.getGpsPosition() == null) {
        return null;
    }

    Point geoPos = JTSUtil.getPoint(mbPlaceEntity);

    return new BikeStation(
            mbPlaceEntity.getPlaceId(),
            mbPlaceEntity.getGlobalId(),
            geoPos,
            mbPlaceEntity.getProviderId(),
            mbPlaceEntity.getCapacity(),
            mbPlaceEntity.getAvailableCapacity(),
            mbPlaceEntity.getAvailableVehicles(),
            mbPlaceEntity.getName(),
            vehicleStatusList
    );
}
项目:xsharing-services-router    文件:ConverterUtil.java   
public static CarStation toCarStation(MBPlaceEntity mbPlaceEntity, List<VehicleStatus> vehicleStatusList) {
    if (mbPlaceEntity.getGpsPosition() == null) {
        return null;
    }

    Point geoPos = JTSUtil.getPoint(mbPlaceEntity);

    return new CarStation(
            mbPlaceEntity.getPlaceId(),
            mbPlaceEntity.getGlobalId(),
            geoPos,
            mbPlaceEntity.getProviderId(),
            mbPlaceEntity.getCapacity(),
            mbPlaceEntity.getAvailableCapacity(),
            mbPlaceEntity.getAvailableVehicles(),
            mbPlaceEntity.getName(),
            vehicleStatusList
    );
}
项目:vt-support    文件:JtsAdapter.java   
/**
 * Get the MVT type mapping for the provided JTS Geometry.
 *
 * @param geometry JTS Geometry to get MVT type for
 * @return MVT type for the given JTS Geometry, may return
 * {@link uk.os.vt.mvt.VectorTile.Tile.GeomType#UNKNOWN}
 */
public static VectorTile.Tile.GeomType toGeomType(Geometry geometry) {
  VectorTile.Tile.GeomType result = VectorTile.Tile.GeomType.UNKNOWN;

  if (geometry instanceof Point
      || geometry instanceof MultiPoint) {
    result = VectorTile.Tile.GeomType.POINT;

  } else if (geometry instanceof LineString
      || geometry instanceof MultiLineString) {
    result = VectorTile.Tile.GeomType.LINESTRING;

  } else if (geometry instanceof Polygon
      || geometry instanceof MultiPolygon) {
    result = VectorTile.Tile.GeomType.POLYGON;
  }

  return result;
}
项目:synthea_java    文件:Person.java   
public void setEmergencyProvider(Provider provider) {
  if (provider == null) {
    Point personLocation = (Point) attributes.get(Person.COORDINATE);
    provider = Hospital.findClosestEmergency(personLocation);
  }
  attributes.put(PREFERREDEMERGENCYPROVIDER, provider);
}
项目:sumo    文件:MaskGeometries.java   
public boolean contains(int x, int y) {
    GeometryFactory gf = new GeometryFactory();
    Point geom = gf.createPoint(new Coordinate(x, y));
    for (Geometry p : maskGeometries) {
        if (p.contains(geom)) {
            return true;
        }
    }
    return false;
}
项目:sumo    文件:MaskGeometries.java   
/**
 * rasterize the mask clipped with the Rectangle scaled back to full size with an offset onto a BufferedImage
 */
public BufferedImage rasterizeJTS(Rectangle rect, int offsetX, int offsetY, double scalingFactor) {

    // create the buffered image of the size of the Rectangle
    BufferedImage image = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_BYTE_BINARY);
    GeometryFactory gf = new GeometryFactory();

    // define the clipping region in full scale
    Coordinate[] coords = new Coordinate[]{
        new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))),
        new Coordinate((int) (((double) rect.getMaxX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))),
        new Coordinate((int) (((double) rect.getMaxX() / scalingFactor)), (int) (((double) rect.getMaxY() / scalingFactor))),
        new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMaxY() / scalingFactor))),
        new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))),};

    Polygon geom = gf.createPolygon(gf.createLinearRing(coords));

    for (Geometry p : maskGeometries) {
        if (p.intersects(geom)) {
            Geometry pg=p.intersection(geom).buffer(0);
            //Coordinate[] coordsInter=gg.getCoordinates();
            //Polygon pg=gf.createPolygon(coordsInter);

            for(int x=0;x<rect.width;x++){
                for(int y=0;y<rect.height;y++){
                    Point point=gf.createPoint(new Coordinate(rect.x+x,rect.y+y));
                    if(pg.contains(point)){
                try{
                    image.setRGB(x,y, Color.WHITE.getRGB());
                }catch(Exception e){
                    logger.error(e.getMessage()+"  x:"+x+"  y:"+y);
                }
                    }
            }
         }
     }
    }
    return image;

}
项目:sumo    文件:GeometryImage.java   
/**
 *
 * @param timeStampStart
 * @param azimuth
 * @param pixels
 * @return
 */
public GeometryImage(String name,String type,String timeStampStart,double azimuth, Boat[] boats) {
    this.type=type;
    this.name=name;
       //GeometricLayer out = new GeometricLayer("point");
       //setName("VDS Analysis");
    geoms=new ArrayList<>();
    //attsMap=new HashMap<>();
       GeometryFactory gf = new GeometryFactory();
       long runid = System.currentTimeMillis();
       int count=0;
       for (Boat boat : boats) {
           AttributesGeometry atts = new AttributesGeometry(VDSSchema.schema);//, VDSSchema.types);
           atts.set(VDSSchema.ID, count++);
           atts.set(VDSSchema.MAXIMUM_VALUE, boat.getAllMaxValue());
           atts.set(VDSSchema.TILE_AVERAGE, boat.getAllTileAvg());
           atts.set(VDSSchema.TILE_STANDARD_DEVIATION, boat.getAllTileStd());
           atts.set(VDSSchema.THRESHOLD, boat.getAllTrhesh());
           atts.set(VDSSchema.RUN_ID, runid + "");
           atts.set(VDSSchema.NUMBER_OF_AGGREGATED_PIXELS, boat.getSize());
           atts.set(VDSSchema.ESTIMATED_LENGTH, boat.getLength());
           atts.set(VDSSchema.ESTIMATED_WIDTH, boat.getWidth());
           atts.set(VDSSchema.SIGNIFICANCE, boat.getAllSignificance());//(boat.getLength() - boat.getWidth()) / (boat.getWidth() * boat.getHeading()));
           timeStampStart=timeStampStart.replace("Z", "");
           atts.set(VDSSchema.DATE, Timestamp.valueOf(timeStampStart));
           atts.set(VDSSchema.VS, 0);
           //compute the direction of the vessel considering the azimuth of the image result is between 0 and 180 degree
           double degree = boat.getHeading() + 90 + azimuth;
           if (degree > 180) {
               degree = degree - 180;
           }
        degree = degree-90;
           atts.set(VDSSchema.ESTIMATED_HEADING, degree);
           Point p=gf.createPoint(new Coordinate(boat.getPosx(), boat.getPosy()));
           p.setUserData(atts);
           put(p);
       }
   }
项目:sumo    文件:InterpolatedVectorLayer.java   
public void mouseClicked(java.awt.Point imagePosition, int button,Object graphicContext) {
    OpenGLContext context=(OpenGLContext)graphicContext;
    this.selectedGeometry = null;
    GeometryFactory gf = new GeometryFactory();
    Point p = gf.createPoint(new Coordinate(imagePosition.x, imagePosition.y));
    for (Point temp : interpolated) {
        if (temp.isWithinDistance(p, 5 * context.getZoom())) {
            this.selectedGeometry = temp;
            LayerPickedData.put(temp, glayer.getAttributes(temp));
        }
    }
}
项目:sumo    文件:ClipProcess.java   
/**
 * When clipping lines and polygons can turn into multilines and multipolygons
 */
private SimpleFeatureType buildTargetSchema(SimpleFeatureType schema) {
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
        if(ad instanceof GeometryDescriptor) {
            GeometryDescriptor gd = (GeometryDescriptor) ad;
            Class<?> binding = ad.getType().getBinding();
            if(Point.class.isAssignableFrom(binding) || GeometryCollection.class.isAssignableFrom(binding)) {
                tb.add(ad);
            } else {
                Class target;
                if(LineString.class.isAssignableFrom(binding)) {
                    target = MultiLineString.class;
                } else if(Polygon.class.isAssignableFrom(binding)) {
                    target = MultiPolygon.class;
                } else {
                    throw new RuntimeException("Don't know how to handle geometries of type " 
                            + binding.getCanonicalName());
                }
                tb.minOccurs(ad.getMinOccurs());
                tb.maxOccurs(ad.getMaxOccurs());
                tb.nillable(ad.isNillable());
                tb.add(ad.getLocalName(), target, gd.getCoordinateReferenceSystem());
            }
        } else {
            tb.add(ad);
        }
    }
    tb.setName(schema.getName());
    return tb.buildFeatureType();
}
项目:elasticsearch_my    文件:GeoJSONShapeParserTests.java   
public void testParseSimplePoint() throws IOException {
    XContentBuilder pointGeoJson = XContentFactory.jsonBuilder()
            .startObject()
                .field("type", "Point")
                .startArray("coordinates").value(100.0).value(0.0).endArray()
            .endObject();

    Point expected = GEOMETRY_FACTORY.createPoint(new Coordinate(100.0, 0.0));
    assertGeometryEquals(new JtsPoint(expected, SPATIAL_CONTEXT), pointGeoJson);
}
项目:elasticsearch_my    文件:GeoJSONShapeParserTests.java   
public void testParseMultiDimensionShapes() throws IOException {
    // multi dimension point
    XContentBuilder pointGeoJson = XContentFactory.jsonBuilder()
            .startObject()
                .field("type", "Point")
                .startArray("coordinates").value(100.0).value(0.0).value(15.0).value(18.0).endArray()
            .endObject();

    Point expectedPt = GEOMETRY_FACTORY.createPoint(new Coordinate(100.0, 0.0));
    assertGeometryEquals(new JtsPoint(expectedPt, SPATIAL_CONTEXT), pointGeoJson);

    // multi dimension linestring
    XContentBuilder lineGeoJson = XContentFactory.jsonBuilder()
            .startObject()
                .field("type", "LineString")
                .startArray("coordinates")
                    .startArray().value(100.0).value(0.0).value(15.0).endArray()
                    .startArray().value(101.0).value(1.0).value(18.0).value(19.0).endArray()
                .endArray()
            .endObject();

    List<Coordinate> lineCoordinates = new ArrayList<>();
    lineCoordinates.add(new Coordinate(100, 0));
    lineCoordinates.add(new Coordinate(101, 1));

    LineString expectedLS = GEOMETRY_FACTORY.createLineString(
            lineCoordinates.toArray(new Coordinate[lineCoordinates.size()]));
    assertGeometryEquals(jtsGeom(expectedLS), lineGeoJson);
}
项目:elasticsearch_my    文件:GeoJSONShapeParserTests.java   
public void testParseGeometryCollection() throws IOException {
    XContentBuilder geometryCollectionGeoJson = XContentFactory.jsonBuilder()
            .startObject()
                .field("type", "GeometryCollection")
                .startArray("geometries")
                    .startObject()
                        .field("type", "LineString")
                        .startArray("coordinates")
                            .startArray().value(100.0).value(0.0).endArray()
                            .startArray().value(101.0).value(1.0).endArray()
                        .endArray()
                    .endObject()
                    .startObject()
                        .field("type", "Point")
                        .startArray("coordinates").value(102.0).value(2.0).endArray()
                    .endObject()
                .endArray()
            .endObject();

    Shape[] expected = new Shape[2];
    LineString expectedLineString = GEOMETRY_FACTORY.createLineString(new Coordinate[]{
            new Coordinate(100, 0),
            new Coordinate(101, 1),
    });
    expected[0] = jtsGeom(expectedLineString);
    Point expectedPoint = GEOMETRY_FACTORY.createPoint(new Coordinate(102.0, 2.0));
    expected[1] = new JtsPoint(expectedPoint, SPATIAL_CONTEXT);

    //equals returns true only if geometries are in the same order
    assertGeometryEquals(shapeCollection(expected), geometryCollectionGeoJson);
}
项目:openrouteservice    文件:ConcaveHull.java   
/**
 * Transform into GeometryCollection.
 *
 * @param geom input geometry
 * @return a geometry collection
 */
private static GeometryCollection transformIntoPointGeometryCollection(GeometryCollection gc) {
    UniqueCoordinateArrayFilter filter = new UniqueCoordinateArrayFilter();
    gc.apply(filter);
    Coordinate[] coord = filter.getCoordinates();

    Geometry[] geometries = new Geometry[coord.length];
    for (int i = 0; i < coord.length; i++) {
        Coordinate[] c = new Coordinate[]{coord[i]};
        CoordinateArraySequence cs = new CoordinateArraySequence(c);
        geometries[i] = new Point(cs, gc.getFactory());
    }

    return new GeometryCollection(geometries, gc.getFactory());
}
项目:openrouteservice    文件:MemSQLLocationsDataProvider.java   
private PreparedStatement createCategoriesStatement(LocationsRequest request, Connection conn) throws Exception 
{
    String cmdFilter = buildSearchFilter("", request.getSearchFilter()); 

    Geometry geom = request.getGeometry();
    Envelope bbox = request.getBBox();
    if (bbox != null)
        cmdFilter += buildBboxFilter(bbox) + (geom == null ? "" : " AND ");

    if (geom != null)
    {
        if (geom instanceof Point)
        {
            Point p = (Point)geom;
            cmdFilter += String.format("GEOGRAPHY_WITHIN_DISTANCE(%s, GEOGRAPHY_POINT(%.7f, %.7f), %.1f)", _geomColumn, p.getCoordinate().x, p.getCoordinate().y, request.getRadius());
        } 
        else 
        {
            WKTWriter wktWriter = new WKTWriter();
            cmdFilter += String.format("GEOGRAPHY_WITHIN_DISTANCE(%s, \"%s\", %.1f)", _geomColumn, wktWriter.write(geom), request.getRadius());
        }
    }

    if (cmdFilter != "")
        cmdFilter = " WHERE " + cmdFilter;

    String stateText = _categoriesQuery.replace("!where_clause!", cmdFilter);

    return conn.prepareStatement(stateText);    
}
项目:graphium    文件:GeometryUtils.java   
public static Polygon createRectangleWithSideLengthInMeters(Point p, double sideLengthMeters) {
    Envelope env = createEnvelopeInMeters(p, sideLengthMeters);
    Coordinate[] coords = new Coordinate[5];
    coords[0] = new Coordinate(env.getMinX(), env.getMinY());
    coords[1] = new Coordinate(env.getMinX(), env.getMaxY());
    coords[2] = new Coordinate(env.getMaxX(), env.getMaxY());
    coords[3] = new Coordinate(env.getMaxX(), env.getMinY());
    coords[4] = new Coordinate(env.getMinX(), env.getMinY());
    return gm.createPolygon(coords);
}
项目:graphium    文件:TestGeometryUtils.java   
@Test
public void testDistanceAndoyer() {
    double lon1 = 13.0387869603598;
    double lat1 = 47.8201969276863;

    double lon2 = 13.05214066418;
    double lat2 = 47.8202307410127;

    // horizontal distance in sbg - itzling
    Point start = GeometryUtils.createPoint(lon1, lat1, 0, GeometryUtils.WGS84);
    Point end = GeometryUtils.createPoint(lon2 , lat2, 0, GeometryUtils.WGS84);

    double distand = GeometryUtils.distanceAndoyer(start,end);
    System.out.println("Andoyer Distance = " + distand);
}
项目:javaps-geotools-backend    文件:GTHelper.java   
public Feature createFeature(String id, Geometry geometry, SimpleFeatureType featureType) {

        if (geometry == null || geometry.isEmpty()) {
            return null;
        }

        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
        SimpleFeature feature = null;

        Object[] newData = new Object[featureType.getDescriptors().size()];

        int i = 0;

        if (geometry.getGeometryType().equals("Point")) {
            Point[] points = new Point[1];
            points[0] = (Point) geometry;
            newData[i] = geometry.getFactory().createMultiPoint(points);
        } else if (geometry.getGeometryType().equals("LineString")) {
            LineString[] lineString = new LineString[1];
            lineString[0] = (LineString) geometry;
            newData[i] = geometry.getFactory().createMultiLineString(lineString);
        } else if (geometry.getGeometryType().equals("Polygon")) {
            Polygon[] polygons = new Polygon[1];
            polygons[0] = (Polygon) geometry;
            newData[i] = geometry.getFactory().createMultiPolygon(polygons);
        } else {
            newData[i] = geometry;
        }

        feature = featureBuilder.buildFeature(id, newData);

        return feature;
    }
项目:fpm    文件:BoundariesA7ShapefileTest.java   
@BeforeClass
public static void setup() {

    TomtomFolder tomtomFolder = mock(TomtomFolder.class);
    when(tomtomFolder.getFile("a7.shp")).thenReturn("src/test/resources/tomtom/boundaries/a7/b___a7.shp");

    NameProvider nameProvider = mock(NameProvider.class);
    when(nameProvider.getAlternateNames(10560000000808L)).thenReturn(of("name", "Brussel Hoofdstad", "name:fr", "Brussel Hoofdstad FR", "name:nl", "Brussel Hoofdstad NL"));
    when(nameProvider.getAlternateNames(10560000000823L)).thenReturn(of("name", "Halle-Vilvoorde", "name:fr", "Halle-Vilvoorde FR", "name:nl", "Halle-Vilvoorde NL"));

    OsmLevelGenerator osmLevelGenerator = mock(OsmLevelGenerator.class);
    when(osmLevelGenerator.getOsmLevel("b", 0)).thenReturn("2");
    when(osmLevelGenerator.getOsmLevel("b", 7)).thenReturn("7");

    CapitalProvider capitalProvider = mock(CapitalProvider.class);
    Point point = new Point(new PackedCoordinateSequence.Double(new double[]{4.307077, 50.8366041}, 2), new GeometryFactory());
    Point point2 = new Point(new PackedCoordinateSequence.Double(new double[]{4.232918, 50.737785}, 2), new GeometryFactory());
    when(capitalProvider.get(7)).thenReturn(newArrayList(
            new Centroid(10560022000808L, "Brussel Hoofdstad", "21000", 0, 1, 2, point),
            new Centroid(10560033000808L, "Halle", "23000", 7, 1, 10, point2)));

    BoundariesA7Shapefile shapefile = new BoundariesA7Shapefile(tomtomFolder, capitalProvider, nameProvider, osmLevelGenerator);

    shapefile.serialize("target/tests/");

    pbfContent = read(new File("target/tests/a7.osm.pbf"));
}
项目:openrouteservice    文件:ConcaveHull.java   
/**
 * Transform into GeometryCollection.
 *
 * @param geom input geometry
 * @return a geometry collection
 */
private static GeometryCollection transformIntoPointGeometryCollection(Geometry geom) {
    UniqueCoordinateArrayFilter filter = new UniqueCoordinateArrayFilter();
    geom.apply(filter);
    Coordinate[] coord = filter.getCoordinates();

    Geometry[] geometries = new Geometry[coord.length];
    for (int i = 0; i < coord.length; i++) {
        Coordinate[] c = new Coordinate[]{coord[i]};
        CoordinateArraySequence cs = new CoordinateArraySequence(c);
        geometries[i] = new Point(cs, geom.getFactory());
    }

    return new GeometryCollection(geometries, geom.getFactory());
}
项目:fpm    文件:BuiltUpShapefileTest.java   
@BeforeClass
public static void setup() {
    NameProvider nameProvider = mock(NameProvider.class);
    when(nameProvider.getAlternateCityNames(12500001063055L)).thenReturn(newHashMap(of("name:fr", "Rougnat_fr")));
    when(nameProvider.getAlternateCityNames(12500001060481L)).thenReturn(newHashMap(of("name:fr", "Auzances_fr")));
    when(nameProvider.getAlternateCityNames(12500001067545L)).thenReturn(newHashMap(of("name:fr", "La Chaux-Bourdue_fr")));
    when(nameProvider.getAlternateCityNames(112500001060737L)).thenReturn(newHashMap(of("name:fr", "Le Montely_fr")));

    TomtomFolder tomtomFolder = mock(TomtomFolder.class);
    when(tomtomFolder.getFile("bu.shp")).thenReturn("src/test/resources/tomtom/boundaries/bu/rougnat___________bu.shp");

    TownTagger townTagger = mock(TownTagger.class);
    GeometryFactory factory = mock(GeometryFactory.class);

    Point point = new Point(new LiteCoordinateSequence(new double[]{2.5027452, 46.0514552}, 2), factory);
    when(townTagger.getHamlet(12500001063055L)).thenReturn(new Centroid(12500001063055L, "Rougnat", null, 8, 32, 7, point));

    Point point2 = new Point(new LiteCoordinateSequence(new double[]{4.601984, 51.181340}, 2), factory);
    when(townTagger.getHamlet(12500001060481L)).thenReturn(new Centroid(12500001060481L, "Auzances", "456", 8, 32, 8, point2));

    Point point3 = new Point(new LiteCoordinateSequence(new double[]{4.606374, 51.162370}, 2), factory);
    when(townTagger.getHamlet(12500001067545L)).thenReturn(new Centroid(12500001067545L, "La Chaux-Bourdue", "123", 8, 32, 8, point3));

    Point point4 = new Point(new LiteCoordinateSequence(new double[]{4.596975, 51.210989}, 2), factory);
    when(townTagger.getHamlet(12500001060737L)).thenReturn(new Centroid(112500001060737L, "Le Montely", "1011", 8, 32, 8, point4));

    BuiltUpShapefile shapefile = new BuiltUpShapefile(tomtomFolder, nameProvider, townTagger);

    shapefile.serialize("target/tests/");

    pbfContent = read(new File("target/tests/bu.osm.pbf"));
    assertThat(pbfContent.getRelations()).hasSize(4);
}
项目:xsharing-services-router    文件:CarStation.java   
public CarStation(String placeId, String globalId, Point geoPos, String providerId,
                  Integer capacity, Integer availableCapacity, Integer availableVehicles,
                  String name, List<VehicleStatus> vehicleStatusList) {

    super(null, placeId, globalId, geoPos, providerId,
          capacity, availableCapacity, availableVehicles,
          name, vehicleStatusList);
}
项目:xsharing-services-router    文件:JTSUtil.java   
public static Point getPoint(MBPlaceEntity mbPlaceEntity) {
    // Postgres format: (X,Y)
    String input = mbPlaceEntity.getGpsPosition();
    // (X Y)
    String noComma = input.replace(',', ' ');
    // POINT(X Y)
    String prefixed = POINT + noComma;

    return toPoint(prefixed);
}
项目:xsharing-services-router    文件:JTSUtil.java   
/**
 * Input format: POINT(X Y)
 */
private static Point toPoint(String input) {
    try {
        return (Point) reader.read(input);
    } catch (ParseException e) {
        log.error("Could not convert Coordinates {}, got exception {}", input, e.getMessage());
        return null;
    }
}
项目:xsharing-services-router    文件:PointSerializer.java   
@Override
public void serialize(Point value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    if (value == null || value.getCoordinate() == null) {
        provider.defaultSerializeNull(jgen);

    } else {
        jgen.writeStartObject();
        jgen.writeObjectField("x", value.getX());
        jgen.writeObjectField("y", value.getY());
        jgen.writeEndObject();
    }
}
项目:vt-support    文件:JtsAdapter.java   
/**
 * <p>Recursively convert a {@link Geometry}, which may be an instance of
 * {@link GeometryCollection} with mixed
 * element types, into a flat list containing only the following {@link Geometry} types:</p>
 * <ul>
 * <li>{@link Point}</li>
 * <li>{@link LineString}</li>
 * <li>{@link Polygon}</li>
 * <li>{@link MultiPoint}</li>
 * <li>{@link MultiLineString}</li>
 * <li>{@link MultiPolygon}</li>
 * </ul>
 * <p>WARNING: Any other Geometry types that were not mentioned in the list above will be
 * discarded!</p>
 * <p>Useful for converting a generic geometry into a list of simple MVT-feature-ready
 * geometries.</p>
 *
 * @param geom geometry to flatten
 * @return list of MVT-feature-ready geometries
 */
public static List<Geometry> flatFeatureList(Geometry geom) {
  final List<Geometry> singleGeoms = new ArrayList<>();
  final Stack<Geometry> geomStack = new Stack<>();

  Geometry nextGeom;
  int nextGeomCount;

  geomStack.push(geom);
  while (!geomStack.isEmpty()) {
    nextGeom = geomStack.pop();

    if (nextGeom instanceof Point
        || nextGeom instanceof MultiPoint
        || nextGeom instanceof LineString
        || nextGeom instanceof MultiLineString
        || nextGeom instanceof Polygon
        || nextGeom instanceof MultiPolygon) {

      singleGeoms.add(nextGeom);

    } else if (nextGeom instanceof GeometryCollection) {

      // Push all child geometries
      nextGeomCount = nextGeom.getNumGeometries();
      for (int i = 0; i < nextGeomCount; ++i) {
        geomStack.push(nextGeom.getGeometryN(i));
      }

    }
  }

  return singleGeoms;
}
项目:vt-support    文件:JtsGeomStats.java   
private static FeatureStats pointStats(Geometry geom) {
  final FeatureStats featureStats = new FeatureStats();

  final HashSet<Point> pointSet = new HashSet<>(geom.getNumPoints());
  featureStats.totalPts = geom.getNumPoints();

  for (int i = 0; i < geom.getNumGeometries(); ++i) {
    final Point p = (Point) geom.getGeometryN(i);
    featureStats.repeatedPts += pointSet.add(p) ? 0 : 1;
  }

  return featureStats;
}
项目:vt-support    文件:MvtEncoderTest.java   
private static Point createPoint(String name) {
  Coordinate coord = new Coordinate(RANDOM.nextInt(4096), RANDOM.nextInt(4096));
  Point point = GEOMETRY_FACTORY.createPoint(coord);

  Map<String, Object> attributes = new LinkedHashMap<>();
  attributes.put("id", name.hashCode());
  attributes.put("name", name);
  point.setUserData(attributes);

  return point;
}
项目:vt-support    文件:JtsLayerTest.java   
@Test
public void testAddGeometry() {
  String layerName = "Points of Interest";
  List<Geometry> geometries = new ArrayList<>();

  Point point = createPoint(new int[]{51, 0});

  JtsLayer layer = new JtsLayer(layerName, geometries);
  layer.getGeometries().add(point);

  assertTrue(layer.getGeometries().contains(point));
}