Cut PHP Code Review Time & Bugs into Half with CodeRabbit

Handling Geospatial Data with Laravel Magellan

Last updated on by

Handling Geospatial Data with Laravel Magellan image

Geospatial data is important in many applications, from mapping services to ride-sharing apps and even logistics. Whether you're tracking a fleet of delivery vehicles, building a store locator, or analyzing geographic patterns, the ability to efficiently store, query, and manipulate location data can be a very important skill for developers. With geospatial data you can map objects, events, and other real-world phenomena to a specific geographical area identified by latitude and longitude coordinates.

If you are building applications in this area and using PostgreSQL, you will probably use PostGIS.

PostGIS

PostGIS is an extension for the PostgreSQL relational database that adds support for storing, indexing, and querying geospatial data. PostGIS offers the following features:

  • Spatial Data Storage, for example, points, lines, polygons, and multi-geometries, in both 2D and 3D data.
  • Spatial Indexing
  • Spatial Functions that can allow you to filter and analyze spatial data, measuring distances and areas, intersecting geometries, buffering, and more.
  • Geometry Processing, which allows for the processing and manipulating of geometry data, such as simplification, conversion, and generalization.
  • Storage and processing of raster data, such as elevation data and weather data.
  • Functions for geocoding and reverse geocoding.
  • Integration with third-party tools such as QGIS, GeoServer, MapServer, ArcGIS, and Tableau.

Most cloud providers will already have PostGIS installed and you need to enable it. To enable PostGIS, connect to your database as the postgres user or another super-user account, and run:

CREATE EXTENSION postgis;

Thats it! PostGIS is now enabled.

You can find out what version you have with postgis_full_version().

SELECT PostGIS_Full_Version();

However, if you are running your own system, and want to install PostGIS directly on it yourself, here are some basic instructions.

Laravel and Geospatial Data

Laravel by itself, does not natively support much of the functionality needed to handle and work with geospatial data. But assuming you are using PostgreSQL and have PostGIS already installed it allows you to use the geography and geometry methods in your migrations to add a GEOGRAPHY or GEOMETRY equivalent column with the given spatial type and SRID (Spatial Reference System Identifier). For example:

$table->geography('coordinates', subtype: 'point', srid: 4326);
$table->geometry('positions', subtype: 'point', srid: 0);

This may be all you need in certain cases, but querying geospatial data can be made even easier and you can gain additional functionality with the help of a package like Laravel-Magellan.

Laravel-Magellan

Laravel-Magellan simplifies working with PostGIS by providing built-in tools like parsers and generators for GeoJSON, Well-Known Text (WKT), and Well-Known Binary (WKB). It supports all PostGIS data types in migrations and allows access to PostGIS functions through Builder methods, eliminating the need for raw SQL. It was created by the team at Clickbar and is an improvement on the now archived mstaack/laravel-postgis package (not to be confused with the another Laravel PostGIS package which we will try to cover in a subsequent article).

You can install the package via Composer:

composer require clickbar/laravel-magellan

You can then publish and run the migrations with:

php artisan vendor:publish --tag="magellan-migrations"
php artisan migrate

And finally, you can publish the config file with:

php artisan vendor:publish --tag="magellan-config"

Now instead of using the Laravel default geography and geometry types, Magellan extends the default Schema Blueprint with all PostGIS functions and these methods are prefixed with magellan. e.g.

$table->magellanPoint('location', 4326);
$table->magellanGeometry('location', 4326);
$table->magellanGeography('location', 4326);
$table->magellanBox2D('location', 4326);
$table->magellanBox3D('location', 4326);
$table->magellanLineString('location', 4326);

and many more.

Magellan also provides geometry classes, for common geometries, such as Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon and GeometryCollection.

To create a geometry object you can use the generic <GeometryClass>::make method. For instance, to create a Point, specify its x and y coordinates.

$point = Point::make(26.193056, -80.161111);

The Point class also has the makeGeodetic() factory method, which creates a point from latitude, longitude and altitude coordinates. However, for simplicity our examples will only use latitude and longitude.

$point = Point::makeGeodetic(26.193056, -80.161111);

If you're curious, a geodetic point is a specific location on the Earth's surface defined by its latitude, longitude, and elevation. And a geodetic line is the shortest path between two points on Earth's curved surface.

Scenario

As an example, lets put together a scenario of storing Football (Soccer) stadiums and their locations.

Schema::create('stadiums', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('capacity');
$table->string('country');
$table->magellanPoint('location');
$table->timestamps();
});

Our model could look like this:

class Stadium extends Model
{
use HasFactory;
use HasPostgisColumns;
 
protected $guarded = [];
 
protected array $postgisColumns = [
'location' => [
'type' => 'geometry',
'srid' => 4326,
],
];
}

To add a new Stadium, we could write the following code in a Controller:

Stadium::create([
'name' => 'Old Trafford',
'capacity' => 74310,
'country' => 'United Kingdom',
'location' => Point::makeGeodetic(53.463493, -2.292279),
]);

And to query for the location of a Stadium using Magellan we could write:

$stadium = Stadium::first();
dd($stadium->location);

Which will return something like:

Clickbar\Magellan\Data\Geometries\Point {#1732
#srid: 4326
#dimension: Clickbar\Magellan\Data\Geometries\Dimension {#740
+name: "DIMENSION_2D"
+value: "2D"
}
#x: -2.292279
#y: 53.463493
#z: null
#m: null
}

If we then wanted to access the latitude, longitude and altitude values, we can use the getLatitude(), getLongitude() and getAltitude() methods.

$stadium->location->getLatitude();
$stadium->location->getLongitude();
$stadium->location->getAltitude();

Another big reason to use Laravel Magellan is its extensive query-building features. Whenever you want to use a PostGIS function on a query builder, you will want to use one of the builder methods which are prefixed with st. For example, stSelect, stWhere, stOrWhere, etc.

For example, if we were at a particular location and wanted to know which stadiums are nearby, we could try the following:

use Clickbar\Magellan\Data\Geometries\Point;
use Clickbar\Magellan\Database\PostgisFunctions\ST;
 
$myCurrentPosition = Point::makeGeodetic(53.4634962, -2.2948593);
$stadiumsNearBy = Stadium::select()
->stSelect(ST::distanceSphere($myCurrentPosition, 'location'), 'distance_to_stadium')
->stWhere(ST::distanceSphere($myCurrentPosition, 'location'), '<=', 20000)
->get();

Note: The distances returned by ST::distanceSphere() are in meters.

Laravel Magellan also provides simple validation of geometry in GeoJSON format. For example:

class StoreStadiumRequest extends FormRequest
{
use TransformsGeojsonGeometry;
 
public function rules(): array
{
return [
'name' => ['required', 'string'],
'capacity' => ['required', 'integer'],
'country' => ['required', 'string'],
'location' => ['required', new GeometryGeojsonRule([Point::class])],
];
}
 
public function geometries(): array
{
return ['location'];
}
}

By leveraging PostgreSQL and the PostGIS extension, developers can efficiently store, query, and manipulate location data. Laravel-Magellan further simplifies the process by providing a user-friendly interface to PostGIS functionalities.

Learn more about Laravel Magellan and view the source code on Github.

Yannick Lyn Fatt photo

Research Assistant at Laravel News and Full stack web developer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
NativePHP

Build Native Mobile Apps at Ridiculous Speed with NativePHP

Visit NativePHP
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
NativePHP logo

NativePHP

Build rich mobile apps across iOS and Android from a single Laravel codebase. This changes everything!

NativePHP
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Reset Rate Limits Dynamically with Laravel's clear Method image

Reset Rate Limits Dynamically with Laravel's clear Method

Read article
Manipulate Image URLs in Laravel with the Image Transform Package image

Manipulate Image URLs in Laravel with the Image Transform Package

Read article
Handle Nested Arrays Elegantly with Laravel's fluent() Helper image

Handle Nested Arrays Elegantly with Laravel's fluent() Helper

Read article
Laravel 12.19 Adds a useEloquentBuilder Attribute, a FailOnException Queue Middleware, and More image

Laravel 12.19 Adds a useEloquentBuilder Attribute, a FailOnException Queue Middleware, and More

Read article
Test Deferred Operations Easily with Laravel's withoutDefer Helper image

Test Deferred Operations Easily with Laravel's withoutDefer Helper

Read article
Larallow is a Permissions Package With Support for Scopes image

Larallow is a Permissions Package With Support for Scopes

Read article