PHP code example of opensource-labs-gh / laravel-geo-utils

1. Go to this page and download the library: Download opensource-labs-gh/laravel-geo-utils library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

opensource-labs-gh / laravel-geo-utils example snippets


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

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

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

$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

$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);

$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))"

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,
    ],
];

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

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

[
    'min_lat' => float,
    'max_lat' => float,
    'min_lng' => float,
    'max_lng' => float
]
bash
php artisan geo-utils:test
bash
php artisan geo-utils:test --distance
bash
php artisan geo-utils:test --bbox