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 ::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.
The post Handling Geospatial Data with Laravel Magellan appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.