-
-
Notifications
You must be signed in to change notification settings - Fork 98
Fix NearFilter to support geodesic distance for geographic coordinates #1185
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
c0e5007
Initial plan
Copilot 9ee68a4
Add GeographicLib dependency and geodesic distance calculations for N…
Copilot 00bbff4
Fix geodesic NearFilter by avoiding coordinates at exact origin
Copilot 0adc2ef
Add comprehensive documentation linking to issue #1126
Copilot 798a3dc
Add GeoPoint and GeoNearFilter for explicit geographic coordinate sup…
Copilot 72143db
Implement Task 4: Two-pass query execution for spatial filters
Copilot 4b42c31
Clean up outdated documentation and comments
Copilot 2992732
Update GeoNearFilter JavaDoc to reflect implemented two-pass execution
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
105 changes: 105 additions & 0 deletions
105
nitrite-spatial/src/main/java/org/dizitart/no2/spatial/GeoNearFilter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
148
nitrite-spatial/src/main/java/org/dizitart/no2/spatial/GeoPoint.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | ||
| } | ||
| } |
96 changes: 96 additions & 0 deletions
96
nitrite-spatial/src/main/java/org/dizitart/no2/spatial/GeodesicUtils.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
|
|
||
| /** | ||
| * 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); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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'.