Skip to content
Merged
5 changes: 5 additions & 0 deletions nitrite-spatial/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>net.sf.geographiclib</groupId>
<artifactId>GeographicLib-Java</artifactId>
<version>2.0</version>
</dependency>

<dependency>
<groupId>junit</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* Copyright (c) 2017-2020. Nitrite author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.dizitart.no2.spatial;

import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.util.GeometricShapeFactory;

/**
* Spatial filter for finding geometries near a geographic point,
* using geodesic distance on Earth's surface (WGS84 ellipsoid).
*
* <p>This filter is specifically designed for geographic coordinates (lat/long).
* It always uses geodesic distance calculations, eliminating the ambiguity
* of {@link NearFilter}'s auto-detection.</p>
*
* <p><strong>Usage Example:</strong></p>
* <pre>{@code
* GeoPoint center = new GeoPoint(45.0, -93.2650); // Minneapolis
* collection.find(where("location").geoNear(center, 5000.0)); // 5km radius
* }</pre>
*
* <p><strong>Distance Units:</strong> The distance parameter must be in meters.</p>
*
* <p><strong>Accuracy:</strong> This filter uses two-pass query execution for accurate results:
* Phase 1 performs a fast R-tree bounding box search, and Phase 2 refines results using
* precise JTS geometric operations to eliminate false positives.</p>
*
* @since 4.3.3
* @author Anindya Chatterjee
* @see GeoPoint
* @see NearFilter
*/
class GeoNearFilter extends WithinFilter {

/**
* Creates a filter to find geometries near a GeoPoint.
*
* @param field the field to filter on
* @param point the geographic point to check proximity to
* @param distanceMeters the maximum distance in meters
*/
GeoNearFilter(String field, GeoPoint point, Double distanceMeters) {
super(field, createGeodesicCircle(point.getCoordinate(), distanceMeters));
}

/**
* Creates a filter to find geometries near a coordinate.
* The coordinate is validated to ensure it represents a valid geographic point.
*
* @param field the field to filter on
* @param point the coordinate to check proximity to (x=longitude, y=latitude)
* @param distanceMeters the maximum distance in meters
* @throws IllegalArgumentException if coordinates are not valid geographic coordinates
*/
GeoNearFilter(String field, Coordinate point, Double distanceMeters) {
super(field, createGeodesicCircle(validateAndGetCoordinate(point), distanceMeters));
}

private static Coordinate validateAndGetCoordinate(Coordinate coord) {
double lat = coord.getY();
double lon = coord.getX();

if (lat < -90.0 || lat > 90.0) {
throw new IllegalArgumentException(
"GeoNearFilter requires valid latitude (-90 to 90), got: " + lat);
}
if (lon < -180.0 || lon > 180.0) {
throw new IllegalArgumentException(
"GeoNearFilter requires valid longitude (-180 to 180), got: " + lon);
}

return coord;
}

private static Geometry createGeodesicCircle(Coordinate center, double radiusMeters) {
GeometricShapeFactory shapeFactory = new GeometricShapeFactory();
shapeFactory.setNumPoints(64);
shapeFactory.setCentre(center);

// Always use geodesic calculations for GeoNearFilter
double radiusInDegrees = GeodesicUtils.metersToDegreesRadius(center, radiusMeters);
shapeFactory.setSize(radiusInDegrees * 2);
return shapeFactory.createCircle();
}

@Override
public String toString() {
return "(" + getField() + " geoNear " + getValue() + ")";
}
}
148 changes: 148 additions & 0 deletions nitrite-spatial/src/main/java/org/dizitart/no2/spatial/GeoPoint.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Copyright (c) 2017-2020. Nitrite author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.dizitart.no2.spatial;

import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.PrecisionModel;

import java.io.Serializable;

/**
* Represents a geographic point with latitude and longitude coordinates
* on Earth's surface (WGS84 ellipsoid).
*
* <p>This class provides explicit type safety for geographic coordinates,
* eliminating the ambiguity of auto-detection. It validates coordinates
* on construction and provides clear latitude/longitude accessors.</p>
*
* <p><strong>Usage Example:</strong></p>
* <pre>{@code
* // Create a geographic point for Minneapolis
* GeoPoint minneapolis = new GeoPoint(45.0, -93.2650);
*
* // Use with GeoNearFilter
* collection.find(where("location").geoNear(minneapolis, 5000.0));
* }</pre>
*
* <p><strong>Coordinate Order:</strong> Constructor takes (latitude, longitude)
* which differs from JTS Point (x, y) = (longitude, latitude) to avoid confusion.</p>
*
* @since 4.3.3
* @author Anindya Chatterjee
*/
public class GeoPoint implements Serializable {
private static final long serialVersionUID = 1L;
private static final GeometryFactory FACTORY = new GeometryFactory(new PrecisionModel(), 4326);
private final Point point;
private final double latitude;
private final double longitude;

/**
* Creates a new GeoPoint with the specified geographic coordinates.
*
* @param latitude the latitude in degrees (-90 to 90)
* @param longitude the longitude in degrees (-180 to 180)
* @throws IllegalArgumentException if coordinates are out of valid range
*/
public GeoPoint(double latitude, double longitude) {
validateCoordinates(latitude, longitude);
this.latitude = latitude;
this.longitude = longitude;
this.point = FACTORY.createPoint(new Coordinate(longitude, latitude));
}

/**
* Creates a GeoPoint from a JTS Coordinate.
* The coordinate's Y value is treated as latitude and X as longitude.
*
* @param coordinate the coordinate (x=longitude, y=latitude)
* @throws IllegalArgumentException if coordinates are out of valid range
*/
public GeoPoint(Coordinate coordinate) {
this(coordinate.getY(), coordinate.getX());
}

private void validateCoordinates(double latitude, double longitude) {
if (latitude < -90.0 || latitude > 90.0) {
throw new IllegalArgumentException(
"Latitude must be between -90 and 90 degrees, got: " + latitude);
}
if (longitude < -180.0 || longitude > 180.0) {
throw new IllegalArgumentException(
"Longitude must be between -180 and 180 degrees, got: " + longitude);
}
}

/**
* Gets the latitude in degrees.
*
* @return the latitude (-90 to 90)
*/
public double getLatitude() {
return latitude;
}

/**
* Gets the longitude in degrees.
*
* @return the longitude (-180 to 180)
*/
public double getLongitude() {
return longitude;
}

/**
* Gets the underlying JTS Point.
*
* @return the JTS Point representation
*/
public Point getPoint() {
return point;
}

/**
* Gets the coordinate of this GeoPoint.
*
* @return the coordinate (x=longitude, y=latitude)
*/
public Coordinate getCoordinate() {
return point.getCoordinate();
}

@Override
public String toString() {
return String.format("GeoPoint(lat=%.6f, lon=%.6f)", latitude, longitude);
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
GeoPoint other = (GeoPoint) obj;
return Double.compare(latitude, other.latitude) == 0
&& Double.compare(longitude, other.longitude) == 0;
}

@Override
public int hashCode() {
long latBits = Double.doubleToLongBits(latitude);
long lonBits = Double.doubleToLongBits(longitude);
return (int) (latBits ^ (latBits >>> 32) ^ lonBits ^ (lonBits >>> 32));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright (c) 2017-2020. Nitrite author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.dizitart.no2.spatial;

import net.sf.geographiclib.Geodesic;
import net.sf.geographiclib.GeodesicData;
import org.locationtech.jts.geom.Coordinate;

/**
* Utility class for geodesic distance calculations on Earth's surface.
* This class handles the conversion between meters and degrees of latitude/longitude,
* accounting for the curvature of the Earth using the WGS84 ellipsoid model.
*
* <p>This class is used internally by {@link NearFilter} for backward compatibility
* with auto-detection. For new code, use {@link GeoPoint} and {@link GeoNearFilter}
* for explicit geographic coordinate handling.</p>
*
* @since 4.0
* @author Anindya Chatterjee
*/
class GeodesicUtils {
private static final Geodesic WGS84 = Geodesic.WGS84;

/**
* Determines if coordinates appear to be geographic (lat/long) rather than Cartesian.
* This is a heuristic check based on valid lat/long ranges:
* - Latitude: -90 to 90
* - Longitude: -180 to 180
*
* <p><strong>Limitation:</strong> This heuristic may incorrectly classify Cartesian
* coordinates that happen to fall within ±90°/±180° range (e.g., game world coordinates).</p>
*
* <p><strong>Recommendation:</strong> For new code, use {@link GeoPoint} and
* {@link GeoNearFilter} to explicitly indicate geographic coordinates and avoid
* auto-detection ambiguity.</p>
*
* @param center the coordinate to check
* @return true if the coordinate appears to be geographic, false otherwise
*/
static boolean isGeographic(Coordinate center) {
double x = center.getX();
double y = center.getY();

// Check if coordinates fall within valid lat/long ranges
// We use slightly relaxed bounds to be conservative
return Math.abs(y) <= 90.0 && Math.abs(x) <= 180.0;
Copy link

Copilot AI Oct 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment at line 59 states 'We use slightly relaxed bounds to be conservative', but the code uses exact bounds (90.0 and 180.0) without any relaxation. Either the comment should be corrected or the implementation should match the documented intent of being 'slightly relaxed'.

Suggested change
return Math.abs(y) <= 90.0 && Math.abs(x) <= 180.0;
return Math.abs(y) <= 90.1 && Math.abs(x) <= 180.1;

Copilot uses AI. Check for mistakes.
}

/**
* Calculates the approximate radius in degrees for a given distance in meters
* at a specific geographic coordinate. This accounts for the fact that one degree
* of longitude varies with latitude.
*
* <p>This method calculates geodesic distances in both E-W and N-S directions and
* returns the maximum to ensure complete circular coverage. Combined with the
* two-pass query execution in {@link SpatialIndex}, this provides accurate results
* while maintaining performance.</p>
*
* @param center the center coordinate (longitude, latitude)
* @param radiusMeters the radius in meters
* @return the approximate radius in degrees
*/
static double metersToDegreesRadius(Coordinate center, double radiusMeters) {
double lat = center.getY();
double lon = center.getX();

// Calculate how many degrees we need to go in different directions
// to cover the specified radius in meters

// East-West: Calculate a point at the given distance east
GeodesicData eastPoint = WGS84.Direct(lat, lon, 90.0, radiusMeters);
double lonDiff = Math.abs(eastPoint.lon2 - lon);

// North-South: Calculate a point at the given distance north
GeodesicData northPoint = WGS84.Direct(lat, lon, 0.0, radiusMeters);
double latDiff = Math.abs(northPoint.lat2 - lat);

// Use the maximum of the two to ensure we cover the full circle
// This creates a slightly larger search area but ensures we don't miss points
return Math.max(lonDiff, latDiff);
}
}
Loading