Java Code Examples for org.locationtech.spatial4j.context.SpatialContext#GEO

The following examples show how to use org.locationtech.spatial4j.context.SpatialContext#GEO . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElasticsearchSearchQueryBase.java    From vertexium with Apache License 2.0 6 votes vote down vote up
private ShapeBuilder getCircleBuilder(GeoCircle geoCircle) {
    // NOTE: as of ES7, storing circles is no longer supported so we need approximate the circle with a polygon
    double radius = geoCircle.getRadius();
    double maxSideLengthKm = getSearchIndex().getConfig().getGeocircleToPolygonSideLength();
    maxSideLengthKm = Math.min(radius, maxSideLengthKm);

    // calculate how many points we need to use given the length of a polygon side
    int numberOfPoints = (int) Math.ceil(Math.PI / Math.asin((maxSideLengthKm / (2 * radius))));
    numberOfPoints = Math.min(numberOfPoints, getSearchIndex().getConfig().getGeocircleToPolygonMaxNumSides());

    // Given the number of sides, loop through slices of 360 degrees and calculate the lat/lon at that radius and heading
    SpatialContext spatialContext = SpatialContext.GEO;
    DistanceCalculator distanceCalculator = spatialContext.getDistCalc();
    Point centerPoint = spatialContext.getShapeFactory().pointXY(DistanceUtils.normLonDEG(geoCircle.getLongitude()), DistanceUtils.normLatDEG(geoCircle.getLatitude()));
    ArrayList<GeoPoint> points = new ArrayList<>();
    for (float angle = 360; angle > 0; angle -= 360.0 / numberOfPoints) {
        Point point = distanceCalculator.pointOnBearing(centerPoint, geoCircle.getRadius() * KM_TO_DEG, angle, spatialContext, null);
        points.add(new GeoPoint(point.getY(), point.getX()));
    }

    // Polygons must start/end at the same point, so add the first point onto the end
    points.add(points.get(0));

    return getPolygonBuilder(new GeoPolygon(points, geoCircle.getDescription()));
}
 
Example 2
Source File: SpatialArgsTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void calcDistanceFromErrPct() {
  final SpatialContext ctx = usually() ? SpatialContext.GEO : new Geo3dSpatialContextFactory().newSpatialContext();
  final double DEP = 0.5;//distErrPct

  //the result is the diagonal distance from the center to the closest corner,
  // times distErrPct

  Shape superwide = ctx.makeRectangle(-180, 180, 0, 0);
  //0 distErrPct means 0 distance always
  assertEquals(0, SpatialArgs.calcDistanceFromErrPct(superwide, 0, ctx), 0);
  assertEquals(180 * DEP, SpatialArgs.calcDistanceFromErrPct(superwide, DEP, ctx), 0);

  Shape supertall = ctx.makeRectangle(0, 0, -90, 90);
  assertEquals(90 * DEP, SpatialArgs.calcDistanceFromErrPct(supertall, DEP, ctx), 0);

  Shape upperhalf = ctx.makeRectangle(-180, 180, 0, 90);
  assertEquals(45 * DEP, SpatialArgs.calcDistanceFromErrPct(upperhalf, DEP, ctx), 0.0001);

  Shape midCircle = ctx.makeCircle(0, 0, 45);
  assertEquals(60 * DEP, SpatialArgs.calcDistanceFromErrPct(midCircle, DEP, ctx), 0.0001);
}
 
Example 3
Source File: TestTestFramework.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueries() throws IOException {
  String name = StrategyTestCase.QTEST_Cities_Intersects_BBox;

  InputStream in = getClass().getClassLoader().getResourceAsStream(name);
  SpatialContext ctx = SpatialContext.GEO;
  Iterator<SpatialTestQuery> iter = SpatialTestQuery.getTestQueries(
      new SpatialArgsParser(), ctx, name, in );//closes the InputStream
  List<SpatialTestQuery> tests = new ArrayList<>();
  while( iter.hasNext() ) {
    tests.add( iter.next() );
  }
  Assert.assertEquals( 3, tests.size() );

  SpatialTestQuery sf = tests.get(0);
  // assert
  assertEquals( 1, sf.ids.size() );
  Assert.assertTrue( sf.ids.get(0).equals( "G5391959" ) );
  Assert.assertTrue( sf.args.getShape() instanceof Rectangle);
  assertEquals(SpatialOperation.Intersects, sf.args.getOperation());
}
 
Example 4
Source File: HeatmapFacetCounterTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  super.setUp();
  cellsValidated = cellValidatedNonZero = 0;
  ctx = SpatialContext.GEO;
  shapeFactory = ctx.getShapeFactory();
  grid = new QuadPrefixTree(ctx, randomIntBetween(1, 8));
  strategy = new RecursivePrefixTreeStrategy(grid, getTestClass().getSimpleName());
  if (rarely()) {
    ((PrefixTreeStrategy) strategy).setPointsOnly(true);
  }
}
 
Example 5
Source File: CentroidComponent.java    From query-segmenter with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void init(NamedList args) {
  super.init(args);
  segmenter = new QuerySegmenterDefaultImpl();
  String filename = (String) args.get(FILENAME);
  String separator = (String) args.get(SEPARATOR);
  segmenter.addFileDictionary("centroid", filename, separator, CentroidSegmentDictionaryMemImpl.class);
  this.ctx = SpatialContext.GEO;
}
 
Example 6
Source File: CompositeStrategyTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void setupGeohashGrid(int maxLevels) {
  this.ctx = SpatialContext.GEO;
  //A fairly shallow grid
  if (maxLevels == -1)
    maxLevels = randomIntBetween(1, 3);//max 16k cells (32^3)
  this.grid = new GeohashPrefixTree(ctx, maxLevels);
  this.rptStrategy = newRPT();
}
 
Example 7
Source File: SerializedStrategyTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
  super.setUp();
  this.ctx = SpatialContext.GEO;
  this.strategy = new SerializedDVStrategy(ctx, "serialized");
}
 
Example 8
Source File: TestBBoxStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testOperations() throws IOException {
  //setup
  if (random().nextInt(4) > 0) {//75% of the time choose geo (more interesting to test)
    this.ctx = SpatialContext.GEO;
  } else {
    SpatialContextFactory factory = new SpatialContextFactory();
    factory.geo = false;
    factory.worldBounds = new RectangleImpl(-300, 300, -100, 100, null);
    this.ctx = factory.newSpatialContext();
  }
  this.strategy = BBoxStrategy.newInstance(ctx, "bbox");
  //test we can disable docValues for predicate tests
  if (random().nextBoolean()) {
    FieldType fieldType = new FieldType(((BBoxStrategy)strategy).getFieldType());
    fieldType.setDocValuesType(DocValuesType.NONE);
    strategy = new BBoxStrategy(ctx, strategy.getFieldName(), fieldType);
  }
  for (SpatialOperation operation : SpatialOperation.values()) {
    if (operation == SpatialOperation.Overlaps)
      continue;//unsupported
    testOperationRandomShapes(operation);

    deleteAll();
    commit();
  }
}
 
Example 9
Source File: SpatialExample.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected void init() {
  //Typical geospatial context
  //  These can also be constructed from SpatialContextFactory
  this.ctx = SpatialContext.GEO;

  int maxLevels = 11;//results in sub-meter precision for geohash
  //TODO demo lookup by detail distance
  //  This can also be constructed from SpatialPrefixTreeFactory
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);

  this.strategy = new RecursivePrefixTreeStrategy(grid, "myGeoField");

  this.directory = new ByteBuffersDirectory();
}
 
Example 10
Source File: TestTermQueryPrefixGridStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
  public void testNGramPrefixGridLosAngeles() throws IOException {
    SpatialContext ctx = SpatialContext.GEO;
    TermQueryPrefixTreeStrategy prefixGridStrategy = new TermQueryPrefixTreeStrategy(new QuadPrefixTree(ctx), "geo");

    Shape point = ctx.makePoint(-118.243680, 34.052230);

    Document losAngeles = new Document();
    losAngeles.add(new StringField("name", "Los Angeles", Field.Store.YES));
    for (Field field : prefixGridStrategy.createIndexableFields(point)) {
      losAngeles.add(field);
    }
    losAngeles.add(new StoredField(prefixGridStrategy.getFieldName(), point.toString()));//just for diagnostics

    addDocumentsAndCommit(Arrays.asList(losAngeles));

    // This won't work with simple spatial context...
    SpatialArgsParser spatialArgsParser = new SpatialArgsParser();
    // TODO... use a non polygon query
//    SpatialArgs spatialArgs = spatialArgsParser.parse(
//        "Intersects(POLYGON((-127.00390625 39.8125,-112.765625 39.98828125,-111.53515625 31.375,-125.94921875 30.14453125,-127.00390625 39.8125)))",
//        new SimpleSpatialContext());

//    Query query = prefixGridStrategy.makeQuery(spatialArgs, fieldInfo);
//    SearchResults searchResults = executeQuery(query, 1);
//    assertEquals(1, searchResults.numFound);
  }
 
Example 11
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testShapePair() {
  ctx = SpatialContext.GEO;
  setupCtx2D(ctx);

  Shape leftShape = new ShapePair(ctx.makeRectangle(-74, -56, -8, 1), ctx.makeRectangle(-180, 134, -90, 90), true);
  Shape queryShape = ctx.makeRectangle(-180, 180, -90, 90);
  assertEquals(SpatialRelation.WITHIN, leftShape.relate(queryShape));
}
 
Example 12
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void setupGeohashGrid(int maxLevels) {
  this.ctx = SpatialContext.GEO;
  //A fairly shallow grid, and default 2.5% distErrPct
  if (maxLevels == -1)
    maxLevels = randomIntBetween(1, 3);//max 16k cells (32^3)
  this.grid = new GeohashPrefixTree(ctx, maxLevels);
  this.strategy = newRPT();
}
 
Example 13
Source File: TestBBoxStrategy.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void setupGeo() {
  this.ctx = SpatialContext.GEO;
  this.strategy = BBoxStrategy.newInstance(ctx, "bbox");
}
 
Example 14
Source File: ShapeRectRelationTestCase.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public ShapeRectRelationTestCase() {
  super(SpatialContext.GEO);
}
 
Example 15
Source File: TestPointVectorStrategy.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
  super.setUp();
  this.ctx = SpatialContext.GEO;
}
 
Example 16
Source File: TestSolr4Spatial.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void checkHits(String fieldName, boolean exact, String ptStr, double distKM, double sphereRadius, int count, int ... docIds) throws ParseException {
  if (exact && isBBoxField(fieldName)) {
    return; // bbox field only supports rectangular query
  }
  String [] tests = new String[docIds != null && docIds.length > 0 ? docIds.length + 1 : 1];
  //test for presence of required ids first
  int i = 0;
  if (docIds != null && docIds.length > 0) {
    for (int docId : docIds) {
      tests[i++] = "//result/doc/*[@name='id'][.='" + docId + "']";
    }
  }
  //check total length last; maybe response includes ids it shouldn't.  Nicer to check this last instead of first so
  // that there may be a more specific detailed id to investigate.
  tests[i++] = "*[count(//doc)=" + count + "]";

  //Test using the Lucene spatial syntax
  {
    //never actually need the score but lets test
    String score = randomScoreMode();

    double distDEG = DistanceUtils.dist2Degrees(distKM, DistanceUtils.EARTH_MEAN_RADIUS_KM);
    Point point = SpatialUtils.parsePoint(ptStr, SpatialContext.GEO);
    String circleStr = "BUFFER(POINT(" + point.getX()+" "+point.getY()+")," + distDEG + ")";
    String shapeStr;
    if (exact) {
      shapeStr = circleStr;
    } else {//bbox
      //the GEO is an assumption
      SpatialContext ctx = SpatialContext.GEO;
      Rectangle bbox = ctx.readShapeFromWkt(circleStr).getBoundingBox();
      shapeStr = "ENVELOPE(" + bbox.getMinX() + ", " + bbox.getMaxX() +
          ", " + bbox.getMaxY() + ", " + bbox.getMinY() + ")";
    }

    //FYI default distErrPct=0.025 works with the tests in this file
    assertQ(req(
          "fl", "id", "q","*:*", "rows", "1000",
          "fq", "{!field f=" + fieldName + (score==null?"":" score="+score)
            + "}Intersects(" + shapeStr + ")"),
        tests);
  }
  //Test using geofilt
  {
    assertQ(req(
        "fl", "id", "q", "*:*", "rows", "1000",
        "fq", "{!" + (exact ? "geofilt" : "bbox") + " sfield=" + fieldName + " pt='" + ptStr + "' d=" + distKM + " sphere_radius=" + sphereRadius + "}"),
        tests);
  }

}
 
Example 17
Source File: TestRecursivePrefixTreeStrategy.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void init(int maxLength) {
  this.maxLength = maxLength;
  this.ctx = SpatialContext.GEO;
  GeohashPrefixTree grid = new GeohashPrefixTree(ctx, maxLength);
  this.strategy = new RecursivePrefixTreeStrategy(grid, getClass().getSimpleName());
}
 
Example 18
Source File: SpatialPrefixTreeTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
  super.setUp();
  ctx = SpatialContext.GEO;
}