Gps
in package
GPS coordinate utility class with geospatial operations
Provides GPS coordinate manipulation, conversion, and calculation methods for geospatial applications. Supports decimal degrees and DMS coordinate formats, distance calculations using Haversine formula, bearing computations, coordinate projections, and export formats including GeoJSON and GPX.
Core Features
- Coordinate format conversion (decimal degrees, DMS)
- Great circle distance calculations (miles, km, nautical miles)
- Bearing calculations with compass directions
- Coordinate projection from distance/bearing vectors
- Geofencing operations (point-in-radius checking)
- GeoJSON export (points, circles, feature collections)
- GPX file import/export (waypoints, tracks, routes)
Method Design Pattern
Static Methods are used for:
- Factory methods that create GPS instances (fromDecimal, fromDMS, fromGpxFile)
- Pure utility functions that don't need coordinate state (dmsToDecimal, decimalToDMS)
- Operations on collections of coordinates (exportTrack, exportRoute)
Instance Methods are used for:
- Accessing specific coordinate data (getLatitude, getLongitude, asArray)
- Operations between two coordinate instances (distanceTo, bearingTo, isWithin)
- Formatting/exporting individual coordinate data (toGeoJson, toGpx, __toString)
- Creating new coordinates from current instance (project)
This design allows both stateless utility operations and stateful coordinate manipulations, providing flexibility for different usage patterns.
Usage Examples
$temple = Gps::fromDecimal(31.052948, -97.099264);
$austin = Gps::fromDecimal(30.267200, -97.743100);
$distance = $temple->distanceTo($austin, 'mi'); // ~65.4 miles
$bearing = $temple->bearingTo($austin); // ~195.8 degrees
$projected = $temple->project(100, 45, 'mi'); // 100 miles NE
Tags
Table of Contents
Properties
- $latitude : float
- Latitude coordinate in decimal degrees
- $longitude : float
- Longitude coordinate in decimal degrees
Methods
- __construct() : mixed
- Create GPS coordinate instance from decimal degree values
- __toString() : string
- Convert GPS coordinate to string representation
- asArray() : array{latitude: float, longitude: float, latitude_dms: string, longitude_dms: string}
- Return coordinate data as array with decimal and DMS formats
- bearingTo() : float|string
- Calculate initial bearing to another coordinate with optional compass direction
- decimalToDMS() : string
- Convert decimal degrees to DMS format string
- distanceTo() : float
- Calculate great circle distance to another GPS coordinate
- dmsToDecimal() : float
- Convert DMS coordinate string to decimal degree value
- exportRoute() : string
- Export array of GPS points as GPX route for navigation
- exportTrack() : string
- Export array of GPS points as GPX track with segments
- fromDecimal() : self
- Static factory method to create GPS instance from decimal coordinates
- fromDMS() : self
- Create GPS instance from Degrees/Minutes/Seconds coordinate strings
- fromGpxFile() : array<string|int, Gps>
- Import GPS coordinates from GPX file waypoints
- getLatitude() : float
- Get the latitude coordinate in decimal degrees
- getLatitudeDMS() : string
- Get latitude coordinate in DMS format string
- getLongitude() : float
- Get the longitude coordinate in decimal degrees
- getLongitudeDMS() : string
- Get longitude coordinate in DMS format string
- isWithin() : bool
- Check if this coordinate is within specified distance from center point
- project() : Gps
- Project new coordinate from current position using distance and bearing
- toGeoJson() : array<string|int, mixed>
- Convert GPS coordinate to GeoJSON Point geometry or Feature
- toGeoJsonCircle() : array<string|int, mixed>
- Generate circular polygon geometry approximating radius around coordinate
- toGeoJsonFeatureCollection() : array<string|int, mixed>
- Create GeoJSON FeatureCollection with point and optional circular boundary
- toGpx() : string
- Export GPS coordinate as GPX waypoint for GPS device compatibility
- bearingToCompass() : string
- Convert numeric degree bearing to compass direction string
Properties
$latitude
Latitude coordinate in decimal degrees
protected
float
$latitude
North-south position as decimal degrees. Positive values = northern hemisphere, negative values = southern hemisphere. Valid range: -90.0 to +90.0 degrees.
Decimal degrees latitude (-90.0 to +90.0)
Tags
$longitude
Longitude coordinate in decimal degrees
protected
float
$longitude
East-west position as decimal degrees. Positive values = eastern hemisphere, negative values = western hemisphere. Valid range: -180.0 to +180.0 degrees.
Decimal degrees longitude (-180.0 to +180.0)
Tags
Methods
__construct()
Create GPS coordinate instance from decimal degree values
public
__construct(float $latitude, float $longitude) : mixed
Initializes GPS coordinate with latitude and longitude in decimal degree format. Uses standard geographic coordinate system (WGS84).
Parameters
- $latitude : float
-
Latitude in decimal degrees (-90.0 to +90.0)
- $longitude : float
-
Longitude in decimal degrees (-180.0 to +180.0)
Tags
__toString()
Convert GPS coordinate to string representation
public
__toString() : string
Returns coordinates as "latitude, longitude" format for debugging, logging, and display purposes.
Tags
Return values
string —Formatted coordinate string "latitude, longitude"
asArray()
Return coordinate data as array with decimal and DMS formats
public
asArray() : array{latitude: float, longitude: float, latitude_dms: string, longitude_dms: string}
Provides comprehensive coordinate data in both decimal degrees and DMS formats. Useful for API responses, data export, and display purposes.
Tags
Return values
array{latitude: float, longitude: float, latitude_dms: string, longitude_dms: string} —Complete coordinate data
bearingTo()
Calculate initial bearing to another coordinate with optional compass direction
public
bearingTo(Gps $other[, bool $asDirection = false ]) : float|string
Computes initial compass bearing using spherical trigonometry. Can return numeric bearing in degrees or compass direction string.
Bearing reference: 0°=North, 90°=East, 180°=South, 270°=West
Parameters
- $other : Gps
-
Target GPS coordinate for bearing calculation
- $asDirection : bool = false
-
If true, returns compass string (e.g., 'NW')
Tags
Return values
float|string —Degrees (0.0-360.0) or compass direction string
decimalToDMS()
Convert decimal degrees to DMS format string
public
static decimalToDMS(float $decimal, string $type) : string
Converts decimal degree coordinate to Degrees/Minutes/Seconds string format with appropriate cardinal direction. Handles latitude and longitude coordinate types.
Formula breakdown: Extract degrees, calculate minutes and seconds from remainder. Cardinal directions: lat = N/S, lon = E/W based on positive/negative values.
Parameters
- $decimal : float
-
Decimal degree coordinate value
- $type : string
-
Coordinate type ('lat' for latitude, 'lon' for longitude)
Tags
Return values
string —DMS formatted string (e.g., "31°03'10.60"N")
distanceTo()
Calculate great circle distance to another GPS coordinate
public
distanceTo(Gps $other[, string $unit = 'mi' ]) : float
Uses Haversine formula to compute shortest distance between two points on Earth's surface. Supports miles, kilometers, and nautical miles.
Earth radius constants: 3958.8 mi, 6371.0 km, 3440.1 nmi Accuracy: ±0.5% for most terrestrial distances.
Parameters
- $other : Gps
-
Target GPS coordinate for distance calculation
- $unit : string = 'mi'
-
Distance unit ('mi', 'km', or 'nmi')
Tags
Return values
float —Distance between coordinates in specified unit
dmsToDecimal()
Convert DMS coordinate string to decimal degree value
public
static dmsToDecimal(string $dms) : float
Parses Degrees/Minutes/Seconds strings into decimal degrees using regex pattern matching. Handles multiple separator styles and cardinal directions.
Formula: Decimal = Degrees + (Minutes/60) + (Seconds/3600) Applied sign based on cardinal direction (S/W = negative).
Parameters
- $dms : string
-
DMS coordinate string (e.g., "31°03'10.6"N")
Tags
Return values
float —Decimal degree value with appropriate sign
exportRoute()
Export array of GPS points as GPX route for navigation
public
static exportRoute(array<string|int, Gps> $points[, string $routeName = 'Route' ]) : string
Creates GPX 1.1 compliant route file from GPS coordinate array. Routes represent planned navigation paths with sequential route points.
Parameters
- $points : array<string|int, Gps>
-
Array of GPS coordinate instances for route
- $routeName : string = 'Route'
-
Name for the route (default: 'Route')
Tags
Return values
string —Complete GPX XML string ready for file export
exportTrack()
Export array of GPS points as GPX track with segments
public
static exportTrack(array<string|int, Gps> $points[, string $trackName = 'Track' ]) : string
Creates GPX 1.1 compliant track file from GPS coordinate array. Tracks represent recorded paths with sequential track points in track segments.
Parameters
- $points : array<string|int, Gps>
-
Array of GPS coordinate instances for track
- $trackName : string = 'Track'
-
Name for the track (default: 'Track')
Tags
Return values
string —Complete GPX XML string ready for file export
fromDecimal()
Static factory method to create GPS instance from decimal coordinates
public
static fromDecimal(float $latitude, float $longitude) : self
Provides fluent interface for creating GPS instances. Functionally equivalent to constructor but offers better readability in method chaining.
Parameters
- $latitude : float
-
Latitude in decimal degrees (-90.0 to +90.0)
- $longitude : float
-
Longitude in decimal degrees (-180.0 to +180.0)
Tags
Return values
self —New GPS coordinate instance
fromDMS()
Create GPS instance from Degrees/Minutes/Seconds coordinate strings
public
static fromDMS(string $latStr, string $lonStr) : self
Parses DMS coordinate strings and converts to decimal degrees. Supports multiple formats: "31°03'10.6"N", "31:03:10.6N", "31 03 10.6 N".
Parameters
- $latStr : string
-
Latitude DMS string (e.g., "31°03'10.6"N")
- $lonStr : string
-
Longitude DMS string (e.g., "97°05'57.4"W")
Tags
Return values
self —New GPS coordinate instance
fromGpxFile()
Import GPS coordinates from GPX file waypoints
public
static fromGpxFile(string $filename) : array<string|int, Gps>
Parses GPX files and extracts waypoint coordinates into GPS instances. Supports standard GPX 1.1 format with basic error handling.
Parameters
- $filename : string
-
Path to GPX file for import
Tags
Return values
array<string|int, Gps> —Array of GPS instances from file waypoints
getLatitude()
Get the latitude coordinate in decimal degrees
public
getLatitude() : float
Returns north-south coordinate. Positive = northern hemisphere, negative = southern hemisphere.
Tags
Return values
float —Latitude in decimal degrees (-90.0 to +90.0)
getLatitudeDMS()
Get latitude coordinate in DMS format string
public
getLatitudeDMS() : string
Returns latitude as Degrees/Minutes/Seconds string with cardinal direction. Uses decimalToDMS() internally with 'lat' type parameter.
Tags
Return values
string —Latitude in DMS format (e.g., "31°03'10.60"N")
getLongitude()
Get the longitude coordinate in decimal degrees
public
getLongitude() : float
Returns east-west coordinate. Positive = eastern hemisphere, negative = western hemisphere.
Tags
Return values
float —Longitude in decimal degrees (-180.0 to +180.0)
getLongitudeDMS()
Get longitude coordinate in DMS format string
public
getLongitudeDMS() : string
Returns longitude as Degrees/Minutes/Seconds string with cardinal direction. Uses decimalToDMS() internally with 'lon' type parameter.
Tags
Return values
string —Longitude in DMS format (e.g., "97°05'57.40"W")
isWithin()
Check if this coordinate is within specified distance from center point
public
isWithin(float $distance, Gps $center[, string $unit = 'mi' ]) : bool
Performs geofencing validation by calculating distance from center and comparing against radius. Uses same Haversine calculation as distanceTo().
Parameters
- $distance : float
-
Maximum distance (radius) for inclusion
- $center : Gps
-
Center point for distance measurement
- $unit : string = 'mi'
-
Distance unit ('mi', 'km', or 'nmi')
Tags
Return values
bool —True if this coordinate is within the specified radius
project()
Project new coordinate from current position using distance and bearing
public
project(float $distance, float $bearing[, string $unit = 'mi' ]) : Gps
Calculates new GPS coordinate by projecting specified distance in given direction using spherical trigonometry. Accounts for Earth's curvature.
Parameters
- $distance : float
-
Distance to project in specified unit
- $bearing : float
-
Direction in degrees (0° = North, clockwise)
- $unit : string = 'mi'
-
Distance unit ('mi', 'km', or 'nmi')
Tags
Return values
Gps —New GPS coordinate at projected location
toGeoJson()
Convert GPS coordinate to GeoJSON Point geometry or Feature
public
toGeoJson([bool $asFeature = false ]) : array<string|int, mixed>
Exports GPS coordinate as GeoJSON-compliant structure. Supports Point geometry or full Feature object. Uses [longitude, latitude] coordinate order.
Parameters
- $asFeature : bool = false
-
If true, returns Feature object; if false, returns Point geometry
Tags
Return values
array<string|int, mixed> —GeoJSON-compliant array structure
toGeoJsonCircle()
Generate circular polygon geometry approximating radius around coordinate
public
toGeoJsonCircle(float $radius[, int $segments = 64 ][, string $unit = 'mi' ]) : array<string|int, mixed>
Creates GeoJSON Polygon geometry approximating circle with specified radius. Uses coordinate projection to generate evenly-spaced polygon vertices.
Parameters
- $radius : float
-
Circle radius in specified unit
- $segments : int = 64
-
Number of polygon vertices (default: 64)
- $unit : string = 'mi'
-
Distance unit ('mi', 'km', or 'nmi')
Tags
Return values
array<string|int, mixed> —GeoJSON Polygon geometry with circular approximation
toGeoJsonFeatureCollection()
Create GeoJSON FeatureCollection with point and optional circular boundary
public
toGeoJsonFeatureCollection([float $radius = 0 ][, int $segments = 64 ][, string $unit = 'mi' ]) : array<string|int, mixed>
Generates complete GeoJSON FeatureCollection containing GPS coordinate as Feature point and optionally includes circular polygon for radius boundary.
Parameters
- $radius : float = 0
-
Optional radius for circular boundary (0 = no circle)
- $segments : int = 64
-
Number of points in circle polygon (default: 64)
- $unit : string = 'mi'
-
Distance unit for radius ('mi', 'km', or 'nmi')
Tags
Return values
array<string|int, mixed> —Complete GeoJSON FeatureCollection array
toGpx()
Export GPS coordinate as GPX waypoint for GPS device compatibility
public
toGpx([string $name = 'Waypoint' ]) : string
Creates complete GPX 1.1 XML document containing single waypoint with current GPS coordinate. Compatible with GPS devices and mapping software.
Parameters
- $name : string = 'Waypoint'
-
Waypoint name for GPS device display (default: 'Waypoint')
Tags
Return values
string —Complete GPX XML document ready for file export
bearingToCompass()
Convert numeric degree bearing to compass direction string
protected
static bearingToCompass(float $degrees) : string
Maps bearing in degrees to 16-point compass rose direction. Used internally by bearingTo() when compass direction string is requested.
Direction mapping: 0°=N, 22.5°=NNE, 45°=NE, etc.
Parameters
- $degrees : float
-
Bearing in degrees (0.0-360.0)
Tags
Return values
string —Compass point abbreviation (N, NNE, NE, ENE, etc.)