Java Code Examples for org.locationtech.spatial4j.shape.Point#getX()

The following examples show how to use org.locationtech.spatial4j.shape.Point#getX() . 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: CompositeStrategyTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private Shape randomCircle() {
  final Point point = randomPoint();
  //TODO pick using gaussian
  double radius;
  if (ctx.isGeo()) {
    radius = randomDouble() * 100;
  } else {
    //find distance to closest edge
    final Rectangle worldBounds = ctx.getWorldBounds();
    double maxRad = point.getX() - worldBounds.getMinX();
    maxRad = Math.min(maxRad, worldBounds.getMaxX() - point.getX());
    maxRad = Math.min(maxRad, point.getY() - worldBounds.getMinY());
    maxRad = Math.min(maxRad, worldBounds.getMaxY() - point.getY());
    radius = randomDouble() * maxRad;
  }

  return ctx.makeCircle(point, radius);
}
 
Example 2
Source File: LatLonPointSpatialField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Field[] createIndexableFields(Shape shape) {
  if (!(shape instanceof Point)) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        getClass().getSimpleName() + " only supports indexing points; got: " + shape);
  }
  Point point = (Point) shape;

  int fieldsLen = (indexed ? 1 : 0) + (docValues ? 1 : 0);
  Field[] fields = new Field[fieldsLen];
  int fieldsIdx = 0;
  if (indexed) {
    fields[fieldsIdx++] = new LatLonPoint(getFieldName(), point.getY(), point.getX());
  }
  if (docValues) {
    fields[fieldsIdx++] = new LatLonDocValuesField(getFieldName(), point.getY(), point.getX());
  }
  return fields;
}
 
Example 3
Source File: ElasticsearchIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Iterable<? extends DocumentDistance> geoQuery(final IRI geoProperty, Point p, final IRI units,
		double distance, String distanceVar, Var contextVar) throws MalformedQueryException, IOException {
	double unitDist;
	final DistanceUnit unit;
	if (GEOF.UOM_METRE.equals(units)) {
		unit = DistanceUnit.METERS;
		unitDist = distance;
	} else if (GEOF.UOM_DEGREE.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = unit.getDistancePerDegree() * distance;
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = DistanceUtils.radians2Dist(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else if (GEOF.UOM_UNITY.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = distance * Math.PI * DistanceUtils.EARTH_MEAN_RADIUS_KM;
	} else {
		throw new MalformedQueryException("Unsupported units: " + units);
	}

	double lat = p.getY();
	double lon = p.getX();
	final String fieldName = toGeoPointFieldName(SearchFields.getPropertyField(geoProperty));
	QueryBuilder qb = QueryBuilders.functionScoreQuery(
			QueryBuilders.geoDistanceQuery(fieldName).point(lat, lon).distance(unitDist, unit),
			ScoreFunctionBuilders.linearDecayFunction(fieldName, GeohashUtils.encodeLatLon(lat, lon),
					new DistanceUnit.Distance(unitDist, unit).toString()));
	if (contextVar != null) {
		qb = addContextTerm(qb, (Resource) contextVar.getValue());
	}

	SearchRequestBuilder request = client.prepareSearch();
	SearchHits hits = search(request, qb);
	final GeoPoint srcPoint = new GeoPoint(lat, lon);
	return Iterables.transform(hits, (Function<SearchHit, DocumentDistance>) hit -> {
		return new ElasticsearchDocumentDistance(hit, geoContextMapper, fieldName, units, srcPoint, unit);
	});
}
 
Example 4
Source File: Geo3dDistanceCalculator.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public double distance(Point from, double toX, double toY) {
  GeoPoint fromGeoPoint;
  if (from instanceof Geo3dPointShape) {
    fromGeoPoint = (((Geo3dPointShape) from).shape).getCenter();
  } else {
    fromGeoPoint = new GeoPoint(planetModel,
        from.getY() * DistanceUtils.DEGREES_TO_RADIANS,
        from.getX() * DistanceUtils.DEGREES_TO_RADIANS);
  }
  GeoPoint toGeoPoint = new GeoPoint(planetModel,
      toY * DistanceUtils.DEGREES_TO_RADIANS,
      toX * DistanceUtils.DEGREES_TO_RADIANS);
  return planetModel.surfaceDistance(fromGeoPoint, toGeoPoint) * DistanceUtils.RADIANS_TO_DEGREES;
}
 
Example 5
Source File: Geo3dShape.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private int relate(Point p) {
  GeoPoint point = new GeoPoint(shape.getPlanetModel(),
      p.getY() * DistanceUtils.DEGREES_TO_RADIANS,
      p.getX() * DistanceUtils.DEGREES_TO_RADIANS);

  if (shape.isWithin(point)) {
    return GeoArea.WITHIN;
  }
  return GeoArea.DISJOINT;
}
 
Example 6
Source File: PackedQuadPrefixTree.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Cell getCell(Point p, int level) {
  if (!robust) { // old method
    List<Cell> cells = new ArrayList<>(1);
    buildNotRobustly(xmid, ymid, 0, cells, 0x0L, ctx.getShapeFactory().pointXY(p.getX(), p.getY()), level);
    if (!cells.isEmpty()) {
      return cells.get(0);//note cells could be longer if p on edge
    }
  }

  double currentXmid = xmid;
  double currentYmid = ymid;
  double xp = p.getX();
  double yp = p.getY();
  long  term = 0L;
  int levelLimit = level > maxLevels ? maxLevels : level;
  SpatialRelation rel = SpatialRelation.CONTAINS;
  for (int lvl = 0; lvl < levelLimit; lvl++){
    int quad = battenberg(currentXmid, currentYmid, xp, yp);
    double halfWidth = levelW[lvl + 1];
    double halfHeight = levelH[lvl + 1];
    switch(quad){
      case 0:
        currentXmid -= halfWidth;
        currentYmid += halfHeight;
        break;
      case 1:
        currentXmid += halfWidth;
        currentYmid += halfHeight;
        break;
      case 2:
        currentXmid -= halfWidth;
        currentYmid -= halfHeight;
        break;
      case 3:
        currentXmid += halfWidth;
        currentYmid -= halfHeight;
        break;
      default:
    }
    // set bits for next level
    term |= (((long)(quad))<<(64-((lvl + 1)<<1)));
    // increment level
    term = ((term>>>1)+1)<<1;
  }
  return new PackedQuadCell(term, rel);
}
 
Example 7
Source File: QuadPrefixTree.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Cell getCell(Point p, int level) {
  if (!robust) { // old method
    List<Cell> cells = new ArrayList<>(1);
    buildNotRobustly(xmid, ymid, 0, cells, new BytesRef(maxLevels+1), ctx.getShapeFactory().pointXY(p.getX(),p.getY()), level);
    if (!cells.isEmpty()) {
      return cells.get(0);//note cells could be longer if p on edge
    }
  }

  double currentXmid = xmid;
  double currentYmid = ymid;
  double xp = p.getX();
  double yp = p.getY();
  BytesRef str = new BytesRef(maxLevels+1);
  int levelLimit = level > maxLevels ? maxLevels : level;
  SpatialRelation rel = SpatialRelation.CONTAINS;
  for (int lvl = 0; lvl < levelLimit; lvl++){
    int c = battenberg(currentXmid, currentYmid, xp, yp);
    double halfWidth = levelW[lvl + 1];
    double halfHeight = levelH[lvl + 1];
    switch(c){
      case 0:
        currentXmid -= halfWidth;
        currentYmid += halfHeight;
        break;
      case 1:
        currentXmid += halfWidth;
        currentYmid += halfHeight;
        break;
      case 2:
        currentXmid -= halfWidth;
        currentYmid -= halfHeight;
        break;
      case 3:
        currentXmid += halfWidth;
        currentYmid -= halfHeight;
        break;
      default:
    }
    str.bytes[str.length++] = (byte)('A' + c);
  }
  return new QuadCell(str, rel);
}
 
Example 8
Source File: GeoHashField.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public String toExternal(IndexableField f) {
  Point p = GeohashUtils.decode(f.stringValue(), SpatialContext.GEO);
  return p.getY() + "," + p.getX();
}
 
Example 9
Source File: LatLonType.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Query createSpatialQuery(QParser parser, SpatialOptions options) {
  Point point = SpatialUtils.parsePointSolrException(options.pointStr, SpatialContext.GEO);

  // lat & lon in degrees
  double latCenter = point.getY();
  double lonCenter = point.getX();
  
  double distDeg = DistanceUtils.dist2Degrees(options.distance, options.radius);
  Rectangle bbox = DistanceUtils.calcBoxByDistFromPtDEG(latCenter, lonCenter, distDeg, SpatialContext.GEO, null);
  double latMin = bbox.getMinY();
  double latMax = bbox.getMaxY();
  double lonMin, lonMax, lon2Min, lon2Max;
  if (bbox.getCrossesDateLine()) {
     lonMin = -180;
     lonMax = bbox.getMaxX();
     lon2Min = bbox.getMinX();
     lon2Max = 180;
  } else {
     lonMin = bbox.getMinX();
     lonMax = bbox.getMaxX();
     lon2Min = -180;
     lon2Max = 180;
  }
  
  IndexSchema schema = parser.getReq().getSchema();
  
  // Now that we've figured out the ranges, build them!
  SchemaField latSF = subField(options.field, LAT, schema);
  SchemaField lonSF = subField(options.field, LON, schema);

  SpatialDistanceQuery spatial = new SpatialDistanceQuery();


  if (options.bbox) {
    BooleanQuery.Builder result = new BooleanQuery.Builder();

    Query latRange = latSF.getType().getRangeQuery(parser, latSF,
              String.valueOf(latMin),
              String.valueOf(latMax),
              true, true);
    result.add(latRange, BooleanClause.Occur.MUST);

    if (lonMin != -180 || lonMax != 180) {
      Query lonRange = lonSF.getType().getRangeQuery(parser, lonSF,
              String.valueOf(lonMin),
              String.valueOf(lonMax),
              true, true);
      if (lon2Min != -180 || lon2Max != 180) {
        // another valid longitude range
        BooleanQuery.Builder bothLons = new BooleanQuery.Builder();
        bothLons.add(lonRange, BooleanClause.Occur.SHOULD);

        lonRange = lonSF.getType().getRangeQuery(parser, lonSF,
              String.valueOf(lon2Min),
              String.valueOf(lon2Max),
              true, true);
        bothLons.add(lonRange, BooleanClause.Occur.SHOULD);

        lonRange = bothLons.build();
      }

      result.add(lonRange, BooleanClause.Occur.MUST);
    }

    spatial.bboxQuery = result.build();
  }


  spatial.origField = options.field.getName();
  spatial.latSource = latSF.getType().getValueSource(latSF, parser);
  spatial.lonSource = lonSF.getType().getValueSource(lonSF, parser);
  spatial.latMin = latMin;
  spatial.latMax = latMax;
  spatial.lonMin = lonMin;
  spatial.lonMax = lonMax;
  spatial.lon2Min = lon2Min;
  spatial.lon2Max = lon2Max;
  spatial.lon2 = lon2Min != -180 || lon2Max != 180;

  spatial.latCenter = latCenter;
  spatial.lonCenter = lonCenter;
  spatial.dist = options.distance;
  spatial.planetRadius = options.radius;

  spatial.calcDist = !options.bbox;

  return spatial;
}
 
Example 10
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);
  }

}