PHPackages                             opensource-labs-gh/laravel-geo-utils - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. opensource-labs-gh/laravel-geo-utils

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

opensource-labs-gh/laravel-geo-utils
====================================

A Laravel utility package for geographic polygon point checks with support for both PHP algorithms and MySQL spatial functions.

v1.0.0(9mo ago)03MITPHPPHP &gt;=8.1CI passing

Since Jul 19Pushed 9mo agoCompare

[ Source](https://github.com/opensource-labs-gh/laravel-geo-utils)[ Packagist](https://packagist.org/packages/opensource-labs-gh/laravel-geo-utils)[ RSS](/packages/opensource-labs-gh-laravel-geo-utils/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (5)Versions (2)Used By (0)

Laravel Geo Utils
=================

[](#laravel-geo-utils)

[![Latest Version on Packagist](https://camo.githubusercontent.com/725e5881e66e492a76f4421b69e68a687e58e7207e3cff0db883e60c52c4fa1b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f70656e736f757263652d6c6162732d67682f6c61726176656c2d67656f2d7574696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/opensource-labs-gh/laravel-geo-utils)[![Total Downloads](https://camo.githubusercontent.com/94c6126574f4d0e39d7ac54bcd7f5e62cbc9b4f571aefae3d91c3af2df581f36/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f70656e736f757263652d6c6162732d67682f6c61726176656c2d67656f2d7574696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/opensource-labs-gh/laravel-geo-utils)[![GitHub Tests Action Status](https://camo.githubusercontent.com/836349a22956b5c068cd61545f3e3e7a3735e0b11275fb237987307ca1940422/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f6f70656e736f757263652d6c6162732d67682f6c61726176656c2d67656f2d7574696c732f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/opensource-labs-gh/laravel-geo-utils/actions?query=workflow%3Arun-tests+branch%3Amain)

A comprehensive Laravel utility package for geographic operations, including polygon point checks, distance calculations, and spatial data manipulation. This package provides both pure PHP implementations and MySQL spatial function integration.

Features
--------

[](#features)

- 🎯 **Point-in-Polygon Detection**: Ray-casting algorithm implementation
- 🚀 **Optimized Performance**: Bounding box pre-filtering for faster checks
- 🗄️ **MySQL Spatial Support**: Leverage MySQL's built-in spatial functions
- 📏 **Distance Calculations**: Haversine formula for accurate distance measurement
- 🔄 **WKT Conversion**: Convert between array and Well-Known Text formats
- ⚡ **Laravel Integration**: Service provider, facade, and Artisan commands
- 🧪 **Comprehensive Testing**: Full test coverage with PHPUnit
- 🛠️ **CLI Tools**: Command-line testing and validation tools

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require opensource-labs-gh/laravel-geo-utils
```

The package will automatically register its service provider and facade.

### Publishing Configuration

[](#publishing-configuration)

Optionally, you can publish the configuration file:

```
php artisan vendor:publish --provider="OpensourceLabsGh\GeoUtils\GeoServiceProvider" --tag="geo-utils-config"
```

Usage
-----

[](#usage)

### Basic Point-in-Polygon Check

[](#basic-point-in-polygon-check)

```
use OpensourceLabsGh\GeoUtils\GeoHelper;
// Or use the facade
use OpensourceLabsGh\GeoUtils\Facades\GeoHelper;

$polygon = [
    ['lat' => 5.6037, 'lng' => -0.1870],
    ['lat' => 5.6037, 'lng' => -0.1700],
    ['lat' => 5.5800, 'lng' => -0.1700],
    ['lat' => 5.5800, 'lng' => -0.1870],
];

$point = ['lat' => 5.5919, 'lng' => -0.1785];

$isInside = GeoHelper::isPointInPolygon($polygon, $point);
// Returns: true
```

### Optimized Point-in-Polygon Check

[](#optimized-point-in-polygon-check)

For better performance with large polygons, use the optimized version that includes bounding box pre-filtering:

```
$isInside = GeoHelper::isPointInPolygonOptimized($polygon, $point);
```

### MySQL Spatial Functions

[](#mysql-spatial-functions)

Use MySQL's built-in spatial functions for potentially better performance:

```
$polygonWkt = GeoHelper::arrayToWktPolygon($polygon);
$isInside = GeoHelper::isPointInPolygonMySQL($polygonWkt, 5.5919, -0.1785);
```

### Distance Calculations

[](#distance-calculations)

Calculate distances between two points using the Haversine formula:

```
$point1 = ['lat' => 37.7749, 'lng' => -122.4194]; // San Francisco
$point2 = ['lat' => 40.7128, 'lng' => -74.0060];  // New York

$distanceKm = GeoHelper::calculateDistance($point1, $point2, 'km');
$distanceMiles = GeoHelper::calculateDistance($point1, $point2, 'miles');
$distanceMeters = GeoHelper::calculateDistance($point1, $point2, 'meters');

// Results:
// $distanceKm ≈ 4135.46
// $distanceMiles ≈ 2569.46
// $distanceMeters ≈ 4135458.97
```

### Bounding Box Operations

[](#bounding-box-operations)

Get the bounding box of a polygon:

```
$boundingBox = GeoHelper::getBoundingBox($polygon);
// Returns:
// [
//     'min_lat' => 5.5800,
//     'max_lat' => 5.6037,
//     'min_lng' => -0.1870,
//     'max_lng' => -0.1700
// ]

// Quick check if point is within bounding box
$isInBounds = GeoHelper::isPointInBoundingBox($boundingBox, $point);
```

### WKT Conversion

[](#wkt-conversion)

Convert array coordinates to Well-Known Text format:

```
$wktPolygon = GeoHelper::arrayToWktPolygon($polygon);
// Returns: "POLYGON((-0.187000 5.603700, -0.170000 5.603700, -0.170000 5.580000, -0.187000 5.580000, -0.187000 5.603700))"
```

Artisan Commands
----------------

[](#artisan-commands)

The package includes a command-line tool for testing and validation:

### Basic Point-in-Polygon Test

[](#basic-point-in-polygon-test)

```
php artisan geo-utils:test
```

### Custom Polygon and Point Test

[](#custom-polygon-and-point-test)

```
php artisan geo-utils:test \
  --polygon='[{"lat":5.6037,"lng":-0.1870},{"lat":5.6037,"lng":-0.1700},{"lat":5.5800,"lng":-0.1700},{"lat":5.5800,"lng":-0.1870}]' \
  --point='{"lat":5.5919,"lng":-0.1785}'
```

### Distance Calculation Test

[](#distance-calculation-test)

```
php artisan geo-utils:test --distance
```

### Bounding Box Test

[](#bounding-box-test)

```
php artisan geo-utils:test --bbox
```

Configuration
-------------

[](#configuration)

The package includes a configuration file with the following options:

```
return [
    'default_distance_unit' => 'km',
    'mysql_spatial_enabled' => true,
    'coordinate_precision' => 6,
    'validation' => [
        'strict_coordinates' => true,
        'min_polygon_points' => 3,
    ],
    'performance' => [
        'use_bounding_box_optimization' => true,
        'cache_bounding_boxes' => false,
    ],
];
```

API Reference
-------------

[](#api-reference)

### GeoHelper Methods

[](#geohelper-methods)

MethodParametersReturnDescription`isPointInPolygon()``array $polygon, array $point``bool`Check if point is inside polygon using ray-casting`isPointInPolygonOptimized()``array $polygon, array $point``bool`Optimized point-in-polygon with bounding box pre-check`isPointInPolygonMySQL()``string $polygonWkt, float $lat, float $lng``bool`MySQL spatial function point-in-polygon check`calculateDistance()``array $point1, array $point2, string $unit``float`Calculate distance between two points`getBoundingBox()``array $polygon``array`Get polygon bounding box`isPointInBoundingBox()``array $boundingBox, array $point``bool`Check if point is in bounding box`arrayToWktPolygon()``array $polygon``string`Convert array coordinates to WKT format### Data Formats

[](#data-formats)

**Point Format:**

```
['lat' => float, 'lng' => float]
```

**Polygon Format:**

```
[
    ['lat' => float, 'lng' => float],
    ['lat' => float, 'lng' => float],
    ['lat' => float, 'lng' => float],
    // ... minimum 3 points required
]
```

**Bounding Box Format:**

```
[
    'min_lat' => float,
    'max_lat' => float,
    'min_lng' => float,
    'max_lng' => float
]
```

Performance Considerations
--------------------------

[](#performance-considerations)

1. **Bounding Box Optimization**: For large polygons, use `isPointInPolygonOptimized()` which performs a quick bounding box check before the full polygon test.
2. **MySQL Spatial Functions**: When working with large datasets, consider using `isPointInPolygonMySQL()` which leverages MySQL's optimized spatial functions.
3. **Coordinate Precision**: Adjust `coordinate_precision` in config based on your needs - higher precision means more accuracy but potentially slower performance.

Error Handling
--------------

[](#error-handling)

The package validates input data and throws `InvalidArgumentException` for:

- Polygons with fewer than 3 points
- Invalid coordinate values (latitude not between -90 and 90, longitude not between -180 and 180)
- Missing required array keys ('lat', 'lng')
- Invalid distance units
- Empty WKT strings

Testing
-------

[](#testing)

Run the package tests:

```
composer test
```

Or run tests with coverage:

```
composer test-coverage
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this project.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Mawuli Agbenyo](https://github.com/opensource-labs-gh)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Changelog
---------

[](#changelog)

Please see [CHANGELOG.md](CHANGELOG.md) for more information about recent changes.

Support
-------

[](#support)

- 📧 Email:
- 🐛 Issues: [GitHub Issues](https://github.com/opensource-labs-gh/laravel-geo-utils/issues)
- 💬 Discussions: [GitHub Discussions](https://github.com/opensource-labs-gh/laravel-geo-utils/discussions)

---

Made with ❤️ by [Opensource Labs Ghana](https://github.com/opensource-labs-gh)

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance57

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

297d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/47bd5516739df8828a46c852f309c5536f7330a2293df8470242094973e80061?d=identicon)[magbenyo](/maintainers/magbenyo)

---

Top Contributors

[![mawuli-agbenyo-creator](https://avatars.githubusercontent.com/u/73019459?v=4)](https://github.com/mawuli-agbenyo-creator "mawuli-agbenyo-creator (25 commits)")

---

Tags

laravelgeometrygisspatialutilitiesgeocoordinatesPolygonpoint in polygon

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/opensource-labs-gh-laravel-geo-utils/health.svg)

```
[![Health](https://phpackages.com/badges/opensource-labs-gh-laravel-geo-utils/health.svg)](https://phpackages.com/packages/opensource-labs-gh-laravel-geo-utils)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[mjaschen/phpgeo

Simple Yet Powerful Geo Library

1.6k8.6M22](/packages/mjaschen-phpgeo)[mostafaznv/nova-map-field

Map Field for Laravel Nova

4693.4k](/packages/mostafaznv-nova-map-field)[funiq/geophp

Open-source native PHP library for doing geometry operations. Can read and write a wide variety of formats: (E)WKT, (E)WKB, TWKB, GeoJSON, KML, GPX, GeoRSS. Works with all Simple-Feature geometries (Point, LineString, Polygon...) and can be used to get centroids, bounding-boxes, area, etc.

21114.4k1](/packages/funiq-geophp)[glhd/special

1929.4k](/packages/glhd-special)[bjuppa/laravel-blog

Add blog functionality to your Laravel project

483.3k2](/packages/bjuppa-laravel-blog)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
