Java Code Examples for org.locationtech.spatial4j.distance.DistanceUtils#dist2Degrees()

The following examples show how to use org.locationtech.spatial4j.distance.DistanceUtils#dist2Degrees() . 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: FunctionArguments.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Convert a value to degrees
 *
 * @param v     value
 * @param units UoM IRI of the unit
 * @return degrees as a double
 * @throws ValueExprEvaluationException
 */
public static double convertToDegrees(double v, IRI units) throws ValueExprEvaluationException {
	double degs;

	if (GEOF.UOM_DEGREE.equals(units)) {
		degs = v;
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		degs = DistanceUtils.toDegrees(v);
	} else if (GEOF.UOM_UNITY.equals(units)) {
		degs = v * 180.0;
	} else if (GEOF.UOM_METRE.equals(units)) {
		degs = DistanceUtils.dist2Degrees(v / 1000.0, DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else {
		throw new ValueExprEvaluationException("Invalid unit of measurement: " + units);
	}
	return degs;
}
 
Example 2
Source File: SpatialPrefixTreeFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected void initMaxLevels() {
  String mlStr = args.get(MAX_LEVELS);
  if (mlStr != null) {
    maxLevels = Integer.valueOf(mlStr);
    return;
  }

  double degrees;
  String maxDetailDistStr = args.get(MAX_DIST_ERR);
  if (maxDetailDistStr == null) {
    if (!ctx.isGeo()) {
      return;//let default to max
    }
    degrees = DistanceUtils.dist2Degrees(DEFAULT_GEO_MAX_DETAIL_KM, DistanceUtils.EARTH_MEAN_RADIUS_KM);
  } else {
    degrees = Double.parseDouble(maxDetailDistStr);
  }
  maxLevels = getLevelForDistance(degrees);
}
 
Example 3
Source File: PortedSolr3Test.java    From lucene-solr with 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 4
Source File: SpatialHelper.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Return a lucene query that finds all points within the given radius from the given point
 */
public static Query findWithin(double longitude, double latitude, double radiusMiles) {
  // Covert the radius in miles to a radius in degrees
  double radiusDEG = DistanceUtils.dist2Degrees(radiusMiles, EARTH_MEAN_RADIUS_MI);

  // Create a query that looks for all points within a circle around the given point
  SpatialArgs args = new SpatialArgs(SpatialOperation.IsWithin,
      new GeoCircle(createPoint(longitude, latitude), radiusDEG, CONTEXT));
  return STRATEGY.makeQuery(args);
}
 
Example 5
Source File: GeoUnits.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static final double fromMiles(double miles, IRI units) {
	double dist;
	if (GEOF.UOM_METRE.equals(units)) {
		dist = DistanceUtils.MILES_TO_KM * miles * 1000.0;
	} else if (GEOF.UOM_DEGREE.equals(units)) {
		dist = DistanceUtils.dist2Degrees(miles, DistanceUtils.EARTH_MEAN_RADIUS_MI);
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		dist = DistanceUtils.dist2Radians(miles, DistanceUtils.EARTH_MEAN_RADIUS_MI);
	} else if (GEOF.UOM_UNITY.equals(units)) {
		dist = miles / (Math.PI * DistanceUtils.EARTH_MEAN_RADIUS_MI);
	} else {
		throw new IllegalArgumentException("Unsupported units: " + units);
	}
	return dist;
}
 
Example 6
Source File: GeoUnits.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static final double fromKilometres(double kms, IRI units) {
	double dist;
	if (GEOF.UOM_METRE.equals(units)) {
		dist = kms * 1000.0;
	} else if (GEOF.UOM_DEGREE.equals(units)) {
		dist = DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		dist = DistanceUtils.dist2Radians(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else if (GEOF.UOM_UNITY.equals(units)) {
		dist = kms / (Math.PI * DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else {
		throw new IllegalArgumentException("Unsupported units: " + units);
	}
	return dist;
}
 
Example 7
Source File: GeoUnits.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static final double toDegrees(double distance, IRI units) {
	final double degs;
	if (GEOF.UOM_METRE.equals(units)) {
		degs = DistanceUtils.dist2Degrees(distance / 1000.0, DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else if (GEOF.UOM_DEGREE.equals(units)) {
		degs = distance;
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		degs = DistanceUtils.RADIANS_TO_DEGREES * distance;
	} else if (GEOF.UOM_UNITY.equals(units)) {
		degs = distance * 180.0;
	} else {
		throw new IllegalArgumentException("Unsupported units: " + units);
	}
	return degs;
}
 
Example 8
Source File: TestRecursivePrefixTreeStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneMeterPrecision() {
  init(GeohashPrefixTree.getMaxLevelsPossible());
  GeohashPrefixTree grid = (GeohashPrefixTree) ((RecursivePrefixTreeStrategy) strategy).getGrid();
  //DWS: I know this to be true.  11 is needed for one meter
  double degrees = DistanceUtils.dist2Degrees(0.001, DistanceUtils.EARTH_MEAN_RADIUS_KM);
  assertEquals(11, grid.getLevelForDistance(degrees));
}
 
Example 9
Source File: TestRecursivePrefixTreeStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrecision() throws IOException{
  init(GeohashPrefixTree.getMaxLevelsPossible());

  Point iPt = ctx.getShapeFactory().pointXY(2.8028712999999925, 48.3708044);//lon, lat
  addDocument(newDoc("iPt", iPt));
  commit();

  Point qPt = ctx.getShapeFactory().pointXY(2.4632387000000335, 48.6003516);

  final double KM2DEG = DistanceUtils.dist2Degrees(1, DistanceUtils.EARTH_MEAN_RADIUS_KM);
  final double DEG2KM = 1 / KM2DEG;

  final double DIST = 35.75;//35.7499...
  assertEquals(DIST, ctx.getDistCalc().distance(iPt, qPt) * DEG2KM, 0.001);

  //distErrPct will affect the query shape precision. The indexed precision
  // was set to nearly zilch via init(GeohashPrefixTree.getMaxLevelsPossible());
  final double distErrPct = 0.025; //the suggested default, by the way
  final double distMult = 1+distErrPct;

  assertTrue(35.74*distMult >= DIST);
  checkHits(q(qPt, 35.74 * KM2DEG, distErrPct), 1, null);

  assertTrue(30*distMult < DIST);
  checkHits(q(qPt, 30 * KM2DEG, distErrPct), 0, null);

  assertTrue(33*distMult < DIST);
  checkHits(q(qPt, 33 * KM2DEG, distErrPct), 0, null);

  assertTrue(34*distMult < DIST);
  checkHits(q(qPt, 34 * KM2DEG, distErrPct), 0, null);
}
 
Example 10
Source File: AbstractSpatialFieldType.java    From lucene-solr with 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 11
Source File: SpatialHelper.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Return a lucene query that finds all points within the given radius from the given point
 */
public static Query findWithin(double longitude, double latitude, double radiusMiles) {
  // Covert the radius in miles to a radius in degrees
  double radiusDEG = DistanceUtils.dist2Degrees(radiusMiles, EARTH_MEAN_RADIUS_MI);

  // Create a query that looks for all points within a circle around the given point
  SpatialArgs args = new SpatialArgs(SpatialOperation.IsWithin,
      new GeoCircle(createPoint(longitude, latitude), radiusDEG, CONTEXT));
  return STRATEGY.makeQuery(args);
}
 
Example 12
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 13
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);
  }

}