Java Code Examples for com.spatial4j.core.distance.DistanceUtils

The following examples show how to use com.spatial4j.core.distance.DistanceUtils. 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
Source Project: linden   Source File: LindenResultParser.java    License: Apache License 2.0 6 votes vote down vote up
private LindenHit parseSpatial(int doc, LindenHit lindenHit) throws IOException {
  if (request.isSetSpatialParam()) {
    Double lat = LindenUtil.getFieldDoubleValue(leaves, doc, LindenSchemaConf.LATITUDE);
    Double lon = LindenUtil.getFieldDoubleValue(leaves, doc, LindenSchemaConf.LONGITUDE);
    if (lat != 0.0 && lon != 0.0) {
      double distance = DistanceUtils.distLawOfCosinesRAD(
          DistanceUtils.toRadians(lat),
          DistanceUtils.toRadians(lon),
          DistanceUtils.toRadians(request.getSpatialParam().getCoordinate().getLatitude()),
          DistanceUtils.toRadians(request.getSpatialParam().getCoordinate().getLongitude()));
      distance = DistanceUtils.radians2Dist(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
      lindenHit.setDistance(distance);
    }
  }
  return lindenHit;
}
 
Example 2
Source Project: lucene-geo-gazetteer   Source File: GeoNameResolver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of location near a certain coordinate. 
 * @param latitude, @param longitude - Center of search area 
 * @param distanceInMiles - Search Radius in miles
 * @param indexerPath - Path to Lucene index
 * @param count - Upper bound to number of results
 * @return - List of locations sorted by population
 * @throws IOException
 */
public List<Location> searchNearby(Double latitude, Double longitude, Double distanceInMiles, String indexerPath, int count) throws IOException {
	
	double distanceInDeg = DistanceUtils.dist2Degrees(distanceInMiles,DistanceUtils.EARTH_EQUATORIAL_RADIUS_MI);
	SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.IsWithin,
			ctx.makeCircle(longitude,latitude, distanceInDeg));
	
	String key = latitude+"-"+longitude;
	Filter filter = strategy.makeFilter(spatialArgs);
	
	IndexSearcher searcher = new IndexSearcher(createIndexReader(indexerPath));
	Sort sort = new Sort(populationSort);
	TopDocs topDocs = searcher.search(new MatchAllDocsQuery(), filter, count, sort);

	ScoreDoc[] scoreDocs = topDocs.scoreDocs;
	HashMap<String, List<Location>> allCandidates = new HashMap<String, List<Location>>();

	getMatchingCandidates(searcher, allCandidates, key, scoreDocs);
	List<Location> results = allCandidates.get(key);
	
	return results;
}
 
Example 3
public Object searchIntersect(OCompositeKey key, double distance, OCommandContext context) throws IOException {

    double lat = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(0), Double.class)).doubleValue();
    double lng = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(1), Double.class)).doubleValue();
    SpatialOperation operation = SpatialOperation.Intersects;

    Point p = ctx.makePoint(lng, lat);
    SpatialArgs args = new SpatialArgs(operation, ctx.makeCircle(lng, lat,
        DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
    Filter filter = strategy.makeFilter(args);
    IndexSearcher searcher = getSearcher();
    ValueSource valueSource = strategy.makeDistanceValueSource(p);
    Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(searcher);

    return new LuceneResultSet(this,
        new SpatialQueryContext(context, searcher, new MatchAllDocsQuery(), filter, distSort).setSpatialArgs(args));
  }
 
Example 4
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test28() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  ShapeReadWriter<SpatialContext> shapeReadWriter = new ShapeReadWriter<SpatialContext>(ctx);
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_KM));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  String writeSpatialArgs = SpatialArgsParser.writeSpatialArgs(args, shapeReadWriter);

  // This has to be done because of rounding.
  SpatialArgs spatialArgs = SpatialArgsParser.parse(writeSpatialArgs, shapeReadWriter);
  Query q1 = sq(strategy.makeQuery(spatialArgs));
  Query q = parseSq("a.id_gis:\"" + writeSpatialArgs + "\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example 5
Source Project: Real-Time-Taxi-Dispatch-Simulator   Source File: NavUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Returns distance (in meters) between 2 points.
 *
 * @param point1 Must not be null
 * @param point2 Must not be null
 * @return distance in meters
 */
public static double getDistance(Point point1, Point point2) {
    Assert.notNull(point1, "point1 must not be null");
    Assert.notNull(point2, "point2 must not be null");

    final SpatialContext ctx = SpatialContext.GEO;
    com.spatial4j.core.shape.Point p1 = ctx.makePoint(point1.getLongitude(), point1.getLatitude());
    com.spatial4j.core.shape.Point p2 = ctx.makePoint(point2.getLongitude(), point2.getLatitude());

    return DistanceUtils.degrees2Dist(ctx.getDistCalc().distance(p1, p2), DistanceUtils.EARTH_MEAN_RADIUS_KM) * 1000;
}
 
Example 6
Source Project: linden   Source File: SpatialFilterConstructor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Filter construct(LindenFilter lindenFilter, LindenConfig config) throws IOException {
  LindenSpatialFilter spatialFilter = lindenFilter.getSpatialFilter();
  SpatialArgs spatialArgs = new SpatialArgs(
      SpatialOperation.Intersects,
      spatialContext.makeCircle(
          spatialFilter.getSpatialParam().coordinate.getLongitude(),
          spatialFilter.getSpatialParam().coordinate.getLatitude(),
          DistanceUtils
              .dist2Degrees(spatialFilter.getSpatialParam().getDistanceRange(), DistanceUtils.EARTH_MEAN_RADIUS_KM)));
  return spatialStrategy.makeFilter(spatialArgs);
}
 
Example 7
Source Project: titan1withtp3.1   Source File: Geoshape.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts this shape into its equivalent Spatial4j {@link Shape}.
 * @return
 */
public Shape convert2Spatial4j() {
    switch(getType()) {
        case POINT: return getPoint().getSpatial4jPoint();
        case CIRCLE: return CTX.makeCircle(getPoint(0).getSpatial4jPoint(), DistanceUtils.dist2Degrees(getRadius(), DistanceUtils.EARTH_MEAN_RADIUS_KM));
        case BOX: return CTX.makeRectangle(getPoint(0).getSpatial4jPoint(),getPoint(1).getSpatial4jPoint());
        case POLYGON: throw new UnsupportedOperationException("Not yet supported");
        default: throw new IllegalStateException("Unrecognized type: " + getType());
    }
}
 
Example 8
Source Project: stratio-cassandra   Source File: GeoCircle.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Shape toSpatial4j(SpatialContext spatialContext) {
    double kms = distance.getValue(GeoDistanceUnit.KILOMETRES);
    double d = DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM);
    return spatialContext.makeCircle(longitude, latitude, d);
}
 
Example 9
@Override
public void onRecordAddedToResultSet(QueryContext queryContext, OContextualRecordId recordId, Document doc, ScoreDoc score) {

  SpatialQueryContext spatialContext = (SpatialQueryContext) queryContext;
  if (spatialContext.spatialArgs != null) {
    Point docPoint = (Point) ctx.readShape(doc.get(strategy.getFieldName()));
    double docDistDEG = ctx.getDistCalc().distance(spatialContext.spatialArgs.getShape().getCenter(), docPoint);
    final double docDistInKM = DistanceUtils.degrees2Dist(docDistDEG, DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM);
    recordId.setContext(new HashMap<String, Object>() {
      {
        put("distance", docDistInKM);
      }
    });
  }
}
 
Example 10
Source Project: orientdb-lucene   Source File: OLuceneNearOperator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object evaluateRecord(OIdentifiable iRecord, ODocument iCurrentResult, OSQLFilterCondition iCondition, Object iLeft,
    Object iRight, OCommandContext iContext) {

  List<Number> left = (List<Number>) iLeft;

  double lat = left.get(0).doubleValue();
  double lon = left.get(1).doubleValue();

  Shape shape = SpatialContext.GEO.makePoint(lon, lat);
  List<Number> right = (List<Number>) iRight;

  double lat1 =  right.get(0).doubleValue();
  double lon1 =  right.get(1).doubleValue();
  Shape shape1 = SpatialContext.GEO.makePoint(lon1, lat1);

  Map map = (Map) right.get(2);
  double distance = 0;

  Number n = (Number) map.get("maxDistance");
  if (n != null) {
    distance = n.doubleValue();
  }
  Point p = (Point) shape1;
  Circle circle = SpatialContext.GEO.makeCircle(p.getX(), p.getY(),
      DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM));
  double docDistDEG = SpatialContext.GEO.getDistCalc().distance((Point) shape, p);
  final double docDistInKM = DistanceUtils.degrees2Dist(docDistDEG, DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM);
  iContext.setVariable("distance", docDistInKM);
  return shape.relate(circle) == SpatialRelation.WITHIN;
}
 
Example 11
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test29() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_KM));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0km))\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example 12
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test30() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example 13
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test45() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(bq(bc_m(strategy.makeQuery(args))));
  Query q = parseSq("<+a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\">");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example 14
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test46() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(bq(bc_m(strategy.makeQuery(args)), bc(tq("rowid", "12345"))));
  Query q = parseSq("<+a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\" rowid:12345>");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example 15
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test47() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("<a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\">");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example 16
Source Project: linden   Source File: SortConstructor.java    License: Apache License 2.0 4 votes vote down vote up
public static Sort constructSort(LindenSearchRequest request, IndexSearcher indexSearcher, LindenConfig config) throws IOException {
  if (!request.isSetSort())
    return null;

  LindenSort lindenSort = request.getSort();
  SortField[] sortFields = new SortField[lindenSort.getFieldsSize()];
  for (int i = 0; i < lindenSort.getFieldsSize(); ++i) {
    LindenSortField field = lindenSort.getFields().get(i);
    SortField.Type type = SortField.Type.STRING;
    boolean isReverse = field.isReverse();
    switch (field.getType()) {
      case STRING:
        type = SortField.Type.STRING;
        break;
      case DOUBLE:
        type = SortField.Type.DOUBLE;
        break;
      case FLOAT:
        type = SortField.Type.FLOAT;
        break;
      case INTEGER:
        type = SortField.Type.INT;
        break;
      case LONG:
        type = SortField.Type.LONG;
        break;
      case SCORE:
        type = SortField.Type.SCORE;
        isReverse = !isReverse;
        break;
      case DISTANCE:
        if (request.isSetSpatialParam()) {
          Point point = SpatialContext.GEO.makePoint(
              request.getSpatialParam().getCoordinate().getLongitude(),
              request.getSpatialParam().getCoordinate().getLatitude());
          ValueSource valueSource = config.getSpatialStrategy().makeDistanceValueSource(point, DistanceUtils.DEG_TO_KM);
          sortFields[i] = valueSource.getSortField(false).rewrite(indexSearcher);
        }
        continue;
    }
    sortFields[i] = new SortField(field.getName(), type, isReverse);
  }
  return new Sort(sortFields);
}
 
Example 17
Source Project: titan1withtp3.1   Source File: Geoshape.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Returns the distance to another point in kilometers
 *
 * @param other Point
 * @return
 */
public double distance(Point other) {
    return DistanceUtils.degrees2Dist(CTX.getDistCalc().distance(getSpatial4jPoint(),other.getSpatial4jPoint()),DistanceUtils.EARTH_MEAN_RADIUS_KM);
}