Java Code Examples for org.locationtech.spatial4j.shape.Point

The following examples show how to use org.locationtech.spatial4j.shape.Point. These examples are extracted from open source projects. 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
protected Shape gridSnap(Shape snapMe) {
  if (snapMe == null)
    return null;
  if (snapMe instanceof ShapePair) {
    ShapePair me = (ShapePair) snapMe;
    return new ShapePair(gridSnap(me.shape1), gridSnap(me.shape2), me.biasContainsThenWithin);
  }
  if (snapMe instanceof Point) {
    snapMe = snapMe.getBoundingBox();
  }
  //The next 4 lines mimic PrefixTreeStrategy.createIndexableFields()
  double distErrPct = ((PrefixTreeStrategy) strategy).getDistErrPct();
  double distErr = SpatialArgs.calcDistanceFromErrPct(snapMe, distErrPct, ctx);
  int detailLevel = grid.getLevelForDistance(distErr);
  CellIterator cells = grid.getTreeCellIterator(snapMe, detailLevel);

  //calc bounding box of cells.
  List<Shape> cellShapes = new ArrayList<>(1024);
  while (cells.hasNext()) {
    Cell cell = cells.next();
    if (!cell.isLeaf())
      continue;
    cellShapes.add(cell.getShape());
  }
  return new ShapeCollection<>(cellShapes, ctx).getBoundingBox();
}
 
Example 2
Source Project: lucene-solr   Source File: PortedSolr3Test.java    License: Apache License 2.0 6 votes vote down vote up
private void _checkHits(boolean bbox, Point pt, double distKM, int assertNumFound, int... assertIds) {
  SpatialOperation op = SpatialOperation.Intersects;
  double distDEG = DistanceUtils.dist2Degrees(distKM, DistanceUtils.EARTH_MEAN_RADIUS_KM);
  Shape shape = shapeFactory.circle(pt, distDEG);
  if (bbox)
    shape = shape.getBoundingBox();

  SpatialArgs args = new SpatialArgs(op,shape);
  //args.setDistPrecision(0.025);
  Query query = strategy.makeQuery(args);
  SearchResults results = executeQuery(query, 100);
  assertEquals(""+shape,assertNumFound,results.numFound);
  if (assertIds != null) {
    Set<Integer> resultIds = new HashSet<>();
    for (SearchResult result : results.results) {
      resultIds.add(Integer.valueOf(result.document.get("id")));
    }
    for (int assertId : assertIds) {
      assertTrue("has " + assertId, resultIds.contains(assertId));
    }
  }
}
 
Example 3
Source Project: crate   Source File: SummitsContext.java    License: Apache License 2.0 6 votes vote down vote up
SummitsContext(String mountain,
               Integer height,
               Integer prominence,
               Point coordinates,
               String region,
               String classification,
               String range,
               String country,
               Integer firstAscent) {
    this.mountain = mountain;
    this.height = height;
    this.prominence = prominence;
    this.coordinates = coordinates;
    this.range = range;
    this.region = region;
    this.classification = classification;
    this.country = country;
    this.firstAscent = firstAscent;
}
 
Example 4
Source Project: lucene-solr   Source File: SpatialExample.java    License: Apache License 2.0 6 votes vote down vote up
private Document newSampleDocument(int id, Shape... shapes) {
  Document doc = new Document();
  doc.add(new StoredField("id", id));
  doc.add(new NumericDocValuesField("id", id));
  //Potentially more than one shape in this field is supported by some
  // strategies; see the javadocs of the SpatialStrategy impl to see.
  for (Shape shape : shapes) {
    for (Field f : strategy.createIndexableFields(shape)) {
      doc.add(f);
    }
    //store it too; the format is up to you
    //  (assume point in this example)
    Point pt = (Point) shape;
    doc.add(new StoredField(strategy.getFieldName(), pt.getX()+" "+pt.getY()));
  }

  return doc;
}
 
Example 5
Source Project: lucene-solr   Source File: LatLonPointSpatialField.java    License: Apache License 2.0 6 votes vote down vote up
protected Query makeQueryFromDocValues(Shape shape) {
      // note: latitude then longitude order for LLP's methods
      if (shape instanceof Circle) {
        Circle circle = (Circle) shape;
        double radiusMeters = circle.getRadius() * DistanceUtils.DEG_TO_KM * 1000;
        return LatLonDocValuesField.newSlowDistanceQuery(getFieldName(),
            circle.getCenter().getY(), circle.getCenter().getX(),
            radiusMeters);
      } else if (shape instanceof Rectangle) {
        Rectangle rect = (Rectangle) shape;
        return LatLonDocValuesField.newSlowBoxQuery(getFieldName(),
            rect.getMinY(), rect.getMaxY(), rect.getMinX(), rect.getMaxX());
      } else if (shape instanceof Point) {
        Point point = (Point) shape;
        return LatLonDocValuesField.newSlowDistanceQuery(getFieldName(),
            point.getY(), point.getX(), 0);
      } else {
        throw new UnsupportedOperationException("Shape " + shape.getClass() + " is not supported by " + getClass());
      }
//      } else if (shape instanceof LucenePolygonShape) {
//        // TODO support multi-polygon
//        Polygon poly = ((LucenePolygonShape)shape).lucenePolygon;
//        return LatLonPoint.newPolygonQuery(getFieldName(), poly);
    }
 
Example 6
Source Project: lucene-solr   Source File: PackedQuadPrefixTree.java    License: Apache License 2.0 6 votes vote down vote up
protected void checkBattenbergNotRobustly(byte quad, double cx, double cy, int level, List<Cell> matches,
                               long term, Shape shape, int maxLevel) {
  // short-circuit if we find a match for the point (no need to continue recursion)
  if (shape instanceof Point && !matches.isEmpty())
    return;
  double w = levelW[level] / 2;
  double h = levelH[level] / 2;

  SpatialRelation v = shape.relate(ctx.getShapeFactory().rect(cx - w, cx + w, cy - h, cy + h));

  if (SpatialRelation.DISJOINT == v) {
    return;
  }

  // set bits for next level
  term |= (((long)(quad))<<(64-(++level<<1)));
  // increment level
  term = ((term>>>1)+1)<<1;

  if (SpatialRelation.CONTAINS == v || (level >= maxLevel)) {
    matches.add(new PackedQuadCell(term, v.transpose()));
  } else {// SpatialRelation.WITHIN, SpatialRelation.INTERSECTS
    buildNotRobustly(cx, cy, level, matches, term, shape, maxLevel);
  }
}
 
Example 7
Source Project: crate   Source File: LiteralValueFormatter.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void formatValue(Object value, StringBuilder builder) {
    if (value == null) {
        builder.append("NULL");
    } else if (value instanceof Map) {
        formatMap((Map<String, Object>) value, builder);
    } else if (value instanceof Collection) {
        formatIterable((Iterable<?>) value, builder);
    } else if (value.getClass().isArray()) {
        formatArray(value, builder);
    } else if (value instanceof String || value instanceof Point || value instanceof Period) {
        builder.append(Literals.quoteStringLiteral(value.toString()));
    } else if (value instanceof Long
               && ((Long) value <= Integer.MAX_VALUE
               || (Long) value >= Integer.MIN_VALUE)) {
        builder.append(value.toString());
        builder.append("::bigint");
    } else {
        builder.append(value.toString());
    }
}
 
Example 8
Source Project: lucene-solr   Source File: SpatialArgs.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Computes the distance given a shape and the {@code distErrPct}.  The
 * algorithm is the fraction of the distance from the center of the query
 * shape to its closest bounding box corner.
 *
 * @param shape Mandatory.
 * @param distErrPct 0 to 0.5
 * @param ctx Mandatory
 * @return A distance (in degrees).
 */
public static double calcDistanceFromErrPct(Shape shape, double distErrPct, SpatialContext ctx) {
  if (distErrPct < 0 || distErrPct > 0.5) {
    throw new IllegalArgumentException("distErrPct " + distErrPct + " must be between [0 to 0.5]");
  }
  if (distErrPct == 0 || shape instanceof Point) {
    return 0;
  }
  Rectangle bbox = shape.getBoundingBox();
  //Compute the distance from the center to a corner.  Because the distance
  // to a bottom corner vs a top corner can vary in a geospatial scenario,
  // take the closest one (greater precision).
  Point ctr = bbox.getCenter();
  double y = (ctr.getY() >= 0 ? bbox.getMaxY() : bbox.getMinY());
  double diagonalDist = ctx.getDistCalc().distance(ctr, bbox.getMaxX(), y);
  return diagonalDist * distErrPct;
}
 
Example 9
Source Project: crate   Source File: GeoPointType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int compare(Point val1, Point val2) {
    if (val1 == null) {
        return -1;
    }
    if (val2 == null) {
        return 1;
    }
    // this is probably not really correct, but should be sufficient for the compareValueTo use case
    // (which is ordering and equality check)
    int latComp = Double.compare(val1.getX(), val2.getX());
    if (latComp != 0) {
        return latComp;
    }
    return Double.compare(val1.getY(), val2.getY());
}
 
Example 10
Source Project: crate   Source File: PointType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
Point decodeUTF8Text(byte[] bytes) {
    String value = new String(bytes, StandardCharsets.UTF_8);
    StringTokenizer tokenizer = new StringTokenizer(value, ",()");
    double x;
    double y;
    if (tokenizer.hasMoreTokens()) {
        x = Double.parseDouble(tokenizer.nextToken());
    } else {
        throw new IllegalArgumentException("Cannot parse input as point: " + value + " expected a point in format: (x, y)");
    }
    if (tokenizer.hasMoreTokens()) {
        y = Double.parseDouble(tokenizer.nextToken());
    } else {
        throw new IllegalArgumentException("Cannot parse input as point: " + value + " expected a point in format: (x, y)");
    }
    return new PointImpl(x, y, JtsSpatialContext.GEO);
}
 
Example 11
Source Project: lucene-solr   Source File: Geo3dDistanceCalculator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Point pointOnBearing(Point from, double distDEG, double bearingDEG, SpatialContext ctx, Point reuse) {
  Geo3dPointShape geoFrom = (Geo3dPointShape) from;
  GeoPoint point = (GeoPoint) geoFrom.shape;
  double dist = DistanceUtils.DEGREES_TO_RADIANS * distDEG;
  double bearing = DistanceUtils.DEGREES_TO_RADIANS * bearingDEG;
  GeoPoint newPoint = planetModel.surfacePointOnBearing(point, dist, bearing);
  double newLat = newPoint.getLatitude() * DistanceUtils.RADIANS_TO_DEGREES;
  double newLon = newPoint.getLongitude() * DistanceUtils.RADIANS_TO_DEGREES;
  if (reuse != null) {
    reuse.reset(newLon, newLat);
    return reuse;
  }
  else {
    return ctx.getShapeFactory().pointXY(newLon, newLat);
  }
}
 
Example 12
Source Project: lucene-solr   Source File: Geo3dShape.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SpatialRelation relate(Shape other) {
  int relationship;
  if (other instanceof Geo3dShape<?>) {
    relationship = relate((Geo3dShape<?>) other);
  } else if (other instanceof Rectangle) {
    relationship = relate((Rectangle) other);
  } else if (other instanceof Point) {
    relationship = relate((Point) other);
  } else {
    throw new RuntimeException("Unimplemented shape relationship determination: " + other.getClass());
  }

  switch (relationship) {
    case GeoArea.DISJOINT:
      return SpatialRelation.DISJOINT;
    case GeoArea.OVERLAPS:
      return (other instanceof Point ? SpatialRelation.CONTAINS : SpatialRelation.INTERSECTS);
    case GeoArea.CONTAINS:
      return (other instanceof Point ? SpatialRelation.CONTAINS : SpatialRelation.WITHIN);
    case GeoArea.WITHIN:
      return SpatialRelation.CONTAINS;
  }

  throw new RuntimeException("Undetermined shape relationship: " + relationship);
}
 
Example 13
Source Project: lucene-solr   Source File: PointVectorStrategy.java    License: Apache License 2.0 6 votes vote down vote up
/** @see #createIndexableFields(org.locationtech.spatial4j.shape.Shape) */
public Field[] createIndexableFields(Point point) {
  Field[] fields = new Field[fieldsLen];
  int idx = -1;
  if (hasStored) {
    fields[++idx] = new StoredField(fieldNameX, point.getX());
    fields[++idx] = new StoredField(fieldNameY, point.getY());
  }
  if (hasDocVals) {
    fields[++idx] = new DoubleDocValuesField(fieldNameX, point.getX());
    fields[++idx] = new DoubleDocValuesField(fieldNameY, point.getY());
  }
  if (hasPointVals) {
    fields[++idx] = new DoublePoint(fieldNameX, point.getX());
    fields[++idx] = new DoublePoint(fieldNameY, point.getY());
  }
  assert idx == fields.length - 1;
  return fields;
}
 
Example 14
Source Project: crate   Source File: DistanceQuery.java    License: Apache License 2.0 6 votes vote down vote up
private static Query eqDistance(Function parentFunction,
                                LuceneQueryBuilder.Context context,
                                String columnName,
                                Double distance,
                                Point lonLat) {
    double smallDistance = distance * 0.99;
    if (smallDistance <= 0.0) {
        return LatLonPoint.newDistanceQuery(columnName, lonLat.getY(), lonLat.getX(), 0);
    }
    Query withinSmallCircle = LatLonPoint.newDistanceQuery(columnName, lonLat.getY(), lonLat.getX(), smallDistance);
    Query withinLargeCircle = LatLonPoint.newDistanceQuery(columnName, lonLat.getY(), lonLat.getX(), distance * 1.01);
    return new BooleanQuery.Builder()
        .add(withinLargeCircle, BooleanClause.Occur.MUST)
        .add(withinSmallCircle, BooleanClause.Occur.MUST_NOT)
        .add(genericFunctionFilter(parentFunction, context), BooleanClause.Occur.FILTER)
        .build();
}
 
Example 15
Source Project: lucene-solr   Source File: PointVectorStrategy.java    License: Apache License 2.0 6 votes vote down vote up
/** @see #createIndexableFields(org.locationtech.spatial4j.shape.Shape) */
public Field[] createIndexableFields(Point point) {
  Field[] fields = new Field[fieldsLen];
  int idx = -1;
  if (hasStored) {
    fields[++idx] = new StoredField(fieldNameX, point.getX());
    fields[++idx] = new StoredField(fieldNameY, point.getY());
  }
  if (hasDocVals) {
    fields[++idx] = new DoubleDocValuesField(fieldNameX, point.getX());
    fields[++idx] = new DoubleDocValuesField(fieldNameY, point.getY());
  }
  if (hasPointVals) {
    fields[++idx] = new DoublePoint(fieldNameX, point.getX());
    fields[++idx] = new DoublePoint(fieldNameY, point.getY());
  }
  if (legacyNumericFieldType != null) {
    fields[++idx] = new LegacyDoubleField(fieldNameX, point.getX(), legacyNumericFieldType);
    fields[++idx] = new LegacyDoubleField(fieldNameY, point.getY(), legacyNumericFieldType);
  }
  assert idx == fields.length - 1;
  return fields;
}
 
Example 16
Source Project: vertexium   Source File: ElasticsearchSearchQueryBase.java    License: 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 17
public LuceneDocumentDistance(ScoreDoc doc, String geoProperty, IRI units, Point origin, boolean includeContext,
		LuceneIndex index) {
	super(doc, index, requiredFields(geoProperty, includeContext));
	this.geoProperty = geoProperty;
	this.units = units;
	this.origin = origin;
}
 
Example 18
Source Project: lucene-solr   Source File: JtsPolygonTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A PrefixTree pruning optimization gone bad.
 * See <a href="https://issues.apache.org/jira/browse/LUCENE-4770">LUCENE-4770</a>.
 */
@Test
public void testBadPrefixTreePrune() throws Exception {

  Shape area = ctx.readShapeFromWkt("POLYGON((-122.83 48.57, -122.77 48.56, -122.79 48.53, -122.83 48.57))");

  SpatialPrefixTree trie = new QuadPrefixTree(ctx, 12);
  TermQueryPrefixTreeStrategy strategy = new TermQueryPrefixTreeStrategy(trie, "geo");
  Document doc = new Document();
  doc.add(new TextField("id", "1", Store.YES));

  Field[] fields = strategy.createIndexableFields(area, 0.025);
  for (Field field : fields) {
    doc.add(field);
  }
  addDocument(doc);

  Point upperleft = ctx.getShapeFactory().pointXY(-122.88, 48.54);
  Point lowerright = ctx.getShapeFactory().pointXY(-122.82, 48.62);

  Query query = strategy.makeQuery(new SpatialArgs(SpatialOperation.Intersects, ctx.getShapeFactory().rect(upperleft, lowerright)));
  commit();

  TopDocs search = indexSearcher.search(query, 10);
  ScoreDoc[] scoreDocs = search.scoreDocs;
  for (ScoreDoc scoreDoc : scoreDocs) {
    System.out.println(indexSearcher.doc(scoreDoc.doc));
  }

  assertEquals(1, search.totalHits.value);
}
 
Example 19
Source Project: lucene-solr   Source File: AbstractSpatialFieldType.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Implemented for compatibility with geofilt &amp; bbox query parsers:
 * {@link SpatialQueryable}.
 */
@Override
public Query createSpatialQuery(QParser parser, SpatialOptions options) {
  Point pt = SpatialUtils.parsePointSolrException(options.pointStr, ctx);

  double distDeg = DistanceUtils.dist2Degrees(options.distance, options.radius);

  Shape shape = ctx.makeCircle(pt, distDeg);
  if (options.bbox)
    shape = shape.getBoundingBox();

  SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, shape);
  return getQueryFromSpatialArgs(parser, options.field, spatialArgs);
}
 
Example 20
@Override
public String toWkt(Shape shape) throws IOException {
	if (shape.isEmpty()) {
		if (shape instanceof Point) {
			return "POINT EMPTY";
		} else if (shape instanceof ShapeCollection) {
			return "GEOMETRYCOLLECTION EMPTY";
		}
	}
	return wktWriter.toString(shape);
}
 
Example 21
Source Project: lucene-solr   Source File: TestPointVectorStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void testInvalidQueryShape() {
  this.strategy = PointVectorStrategy.newInstance(ctx, getClass().getSimpleName());
  Point point = ctx.makePoint(0, 0);
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, point);
  this.strategy.makeQuery(args);
}
 
Example 22
private int compare(Point p1, Point p2) {
	int diff = Double.compare(p1.getX(), p2.getX());
	if (diff == 0) {
		diff = Double.compare(p1.getY(), p2.getY());
	}
	return diff;
}
 
Example 23
@Override
public Shape difference(Shape s1, Shape s2) {
	if (s1 instanceof Point && s2 instanceof Point) {
		Point p1 = (Point) s1;
		Point p2 = (Point) s2;
		int diff = compare(p2, p1);
		if (diff == 0) {
			return createEmptyPoint();
		}
		return s1;
	}
	return notSupported();
}
 
Example 24
Source Project: lucene-solr   Source File: SpatialDocMaker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Optionally converts points to circles, and optionally bbox'es result.
 */
public static ShapeConverter makeShapeConverter(final SpatialStrategy spatialStrategy,
                                                Config config, String configKeyPrefix) {
  //by default does no conversion
  final double radiusDegrees = config.get(configKeyPrefix+"radiusDegrees", 0.0);
  final double plusMinus = config.get(configKeyPrefix+"radiusDegreesRandPlusMinus", 0.0);
  final boolean bbox = config.get(configKeyPrefix + "bbox", false);

  return new ShapeConverter() {
    @Override
    public Shape convert(Shape shape) {
      if (shape instanceof Point && (radiusDegrees != 0.0 || plusMinus != 0.0)) {
        Point point = (Point)shape;
        double radius = radiusDegrees;
        if (plusMinus > 0.0) {
          Random random = new Random(point.hashCode());//use hashCode so it's reproducibly random
          radius += random.nextDouble() * 2 * plusMinus - plusMinus;
          radius = Math.abs(radius);//can happen if configured plusMinus > radiusDegrees
        }
        shape = spatialStrategy.getSpatialContext().makeCircle(point, radius);
      }
      if (bbox)
        shape = shape.getBoundingBox();
      return shape;
    }
  };
}
 
Example 25
@Test
public void pointBearingTest(){
  double radius = 136;
  double distance = 135.97;
  double bearing = 188;
  Point p = ctx.getShapeFactory().pointXY(35, 85);
  Circle circle = ctx.getShapeFactory().circle(p, radius);
  Point bPoint = ctx.getDistCalc().pointOnBearing(p, distance, bearing, ctx, (Point) null);

  double d = ctx.getDistCalc().distance(p, bPoint);
  assertEquals(d, distance, 10-8);

  assertEquals(circle.relate(bPoint), SpatialRelation.CONTAINS);
}
 
Example 26
Source Project: lucene-solr   Source File: PackedQuadPrefixTree.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasNext() {
  if (nextCell != null) {
    return true;
  }
  SpatialRelation rel;
  // loop until we're at the end of the quad tree or we hit a relation
  while (thisCell != null) {
    rel = thisCell.getShape().relate(shape);
    if (rel == SpatialRelation.DISJOINT) {
      thisCell = thisCell.nextCell(false);
    } else { // within || intersects || contains
      thisCell.setShapeRel(rel);
      nextCell = thisCell;
      if (rel == SpatialRelation.WITHIN) {
        thisCell.setLeaf();
        thisCell = thisCell.nextCell(false);
      } else {  // intersects || contains
        level = (short) (thisCell.getLevel());
        if (level == detailLevel || pruned(rel)) {
          thisCell.setLeaf();
          if (shape instanceof Point) {
            thisCell.setShapeRel(SpatialRelation.WITHIN);
            thisCell = null;
          } else {
            thisCell = thisCell.nextCell(false);
          }
          break;
        }
        thisCell = thisCell.nextCell(true);
      }
      break;
    }
  }
  return nextCell != null;
}
 
Example 27
Source Project: lucene-solr   Source File: S2PrefixTree.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CellIterator getTreeCellIterator(Shape shape, int detailLevel) {
    if (!(shape instanceof Point)) {
        return  super.getTreeCellIterator(shape, detailLevel);
    }
    Point p = (Point) shape;
    S2CellId id = S2CellId.fromLatLng(S2LatLng.fromDegrees(p.getY(), p.getX())).parent(arity * (detailLevel - 1));
    List<Cell> cells = new ArrayList<>(detailLevel);
    for (int i=0; i < detailLevel - 1; i++) {
        cells.add(new S2PrefixTreeCell(this, id.parent(i * arity)));
    }
    cells.add(new S2PrefixTreeCell(this, id));
    return new FilterCellIterator(cells.iterator(), null);
}
 
Example 28
Source Project: crate   Source File: GeoPointTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testStreaming() throws Throwable {
    Point p1 = new PointImpl(41.2, -37.4, JtsSpatialContext.GEO);

    BytesStreamOutput out = new BytesStreamOutput();
    DataTypes.GEO_POINT.writeValueTo(out, p1);

    StreamInput in = out.bytes().streamInput();
    Point p2 = DataTypes.GEO_POINT.readValueFrom(in);

    assertThat(p1, equalTo(p2));
}
 
Example 29
Source Project: lucene-solr   Source File: AbstractSpatialFieldType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Query getSpecializedRangeQuery(QParser parser, SchemaField field, String part1, String part2, boolean minInclusive, boolean maxInclusive) {
  if (!minInclusive || !maxInclusive)
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Both sides of spatial range query must be inclusive: " + field.getName());
  Point p1 = SpatialUtils.parsePointSolrException(part1, ctx);
  Point p2 = SpatialUtils.parsePointSolrException(part2, ctx);

  Rectangle bbox = ctx.makeRectangle(p1, p2);
  SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, bbox);
  return getQueryFromSpatialArgs(parser, field, spatialArgs);//won't score by default
}
 
Example 30
Source Project: query-segmenter   Source File: CentroidComponent.java    License: Apache License 2.0 5 votes vote down vote up
private CentroidTypedSegment getClosestSegment(List<TypedSegment> typedSegments, double[] userLatlon) {
  CentroidTypedSegment closest = null;
  double closestDistance = Double.MAX_VALUE;

  for (TypedSegment typedSegment : typedSegments) {
    CentroidTypedSegment centroidSegment = (CentroidTypedSegment) typedSegment;
    Point p1 = new PointImpl(userLatlon[0], userLatlon[1], ctx);
    Point p2 = new PointImpl(centroidSegment.getLatitude(), centroidSegment.getLongitude(), ctx);
    double distance = ctx.getDistCalc().distance(p1, p2);
    if (distance < closestDistance) {
      closest = centroidSegment;
    }
  }
  return closest;
}