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.

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
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
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
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
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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Handling Geospatial Data with Laravel Magellan image

Handling Geospatial Data with Laravel Magellan

Read article
Managing Large Datasets in Laravel with LazyCollection image

Managing Large Datasets in Laravel with LazyCollection

Read article
Collect and Monitor Everything About Sent Emails in Your Laravel App image

Collect and Monitor Everything About Sent Emails in Your Laravel App

Read article
Packagist.org is ending support for Composer 1.x image

Packagist.org is ending support for Composer 1.x

Read article
Mastering Dynamic String Manipulation with Laravel's Str::replaceArray() image

Mastering Dynamic String Manipulation with Laravel's Str::replaceArray()

Read article
Laravel Jobs - December image

Laravel Jobs - December

Read article