package SuMoC.backend.h3; import com.uber.h3core.H3Core; import com.uber.h3core.util.LatLng; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.List; /** * Service for H3 spatial indexing operations. * H3 is a hierarchical hexagonal geospatial indexing system. */ @Service public class H3Service { private final H3Core h3; private final H3Configuration config; public H3Service(H3Configuration config) { this.config = config; try { this.h3 = H3Core.newInstance(); } catch (IOException e) { throw new RuntimeException("Failed to initialize H3Core", e); } } /** * Convert latitude/longitude to H3 cell ID with specific resolution. * * @param latitude Latitude in degrees * @param longitude Longitude in degrees * @param resolution H3 resolution (0-15, higher = more precise) * @return H3 cell ID as hex string */ public String latLngToCell(double latitude, double longitude, int resolution) { return h3.latLngToCellAddress(latitude, longitude, resolution); } /** * Convert latitude/longitude to H3 cell ID using route pattern resolution. * This is typically used for detecting regular trip patterns. * * @param latitude Latitude in degrees * @param longitude Longitude in degrees * @return H3 cell ID as hex string */ public String latLngToCellForRoute(double latitude, double longitude) { return latLngToCell(latitude, longitude, config.getRoutePatternResolution()); } /** * Convert H3 cell ID to center latitude/longitude. * * @param cellId H3 cell ID as hex string * @return LatLng of cell center */ public LatLng cellToLatLng(String cellId) { return h3.cellToLatLng(cellId); } /** * Get all cells within k distance of the given cell (excluding the cell it self). * K-ring distance means cells reachable in k steps on the hexagonal grid. * * @param cellId H3 cell ID as hex string * @param k Distance (number of rings, 0 = only the cell itself) * @return List of H3 cell IDs including the origin cell */ public List getKRingNeighbors(String cellId, int k) { return h3.gridRing(cellId, k); } /** * Get K-ring neighbors using the configured route pattern resolution distance. * Ring means the center cell is not included. * Useful for finding nearby locations when matching trip patterns. * * @param cellId H3 cell ID as hex string * @return List of H3 cell IDs within configured neighbor distance */ public List getRoutePatternNeighbors(String cellId) { return getKRingNeighbors(cellId, config.getRoutePatternNeighborRings()); } }