cowegis/cowegis-geojson
PHP 8.2+ GeoJSON library for the Cowegis project implementing the GeoJSON specification (RFC 7946). Install via Composer (cowegis/cowegis-geojson) to work with GeoJSON data in your PHP applications.
Installation
composer require cowegis/cowegis-geojson
Verify PHP version meets the requirement (^8.2).
First Use Case: Validating GeoJSON Input
use Cowegis\GeoJSON\GeoJSON;
$geoJsonString = '{"type":"Feature","geometry":{"type":"Point","coordinates":[102.0,0.5]},"properties":{"name":"Lake"}}';
$isValid = GeoJSON::isValid($geoJsonString);
if (!$isValid) {
throw new \InvalidArgumentException("Invalid GeoJSON provided.");
}
Where to Look First
GeoJSON (static methods for validation/parsing) and geometry classes (Point, LineString, Polygon, etc.).JsonSerializable for Eloquent models and request validation.Request Validation Use middleware or Form Requests to validate incoming GeoJSON:
// app/Http/Requests/StoreLocationRequest.php
use Cowegis\GeoJSON\GeoJSON;
use Illuminate\Foundation\Http\FormRequest;
public function validateGeoJson($attribute, $value, $fail)
{
if (!GeoJSON::isValid($value)) {
$fail('The '.$attribute.' must be valid GeoJSON.');
}
}
protected function rules()
{
return [
'geometry' => ['required', function ($attribute, $value, $fail) {
$this->validateGeoJson($attribute, $value, $fail);
}],
];
}
Eloquent Model Casting Serialize/deserialize GeoJSON fields automatically:
// app/Models/Location.php
use Cowegis\GeoJSON\GeoJSON;
use Illuminate\Database\Eloquent\Model;
protected $casts = [
'coordinates' => GeoJSON::class, // Automatically encodes/decodes GeoJSON
];
// Usage:
$location = Location::find(1);
$geoJson = $location->coordinates; // Decoded GeoJSON object
$location->coordinates = new \Cowegis\GeoJSON\Point([102.0, 0.5]); // Encoded on save
API Response Formatting Standardize GeoJSON responses in API Resources:
// app/Http/Resources/LocationResource.php
use Cowegis\GeoJSON\GeoJSON;
use Illuminate\Http\Resources\Json\JsonResource;
public function toArray($request)
{
return [
'geometry' => GeoJSON::encode($this->whenLoaded('geometry')),
'properties' => $this->properties,
];
}
Database Storage
Store GeoJSON in PostgreSQL jsonb or MySQL json columns:
// Migration
Schema::create('locations', function (Blueprint $table) {
$table->id();
$table->json('coordinates'); // Stores GeoJSON as JSON
$table->timestamps();
});
// Querying
$locations = Location::whereJsonContains('coordinates', ['type' => 'Point'])->get();
Frontend Integration Ensure outputs are compatible with JavaScript libraries:
// Return GeoJSON for Leaflet/Mapbox
return response()->json([
'type' => 'FeatureCollection',
'features' => GeoJSON::encode($features),
]);
Geofencing Logic Parse GeoJSON polygons to check if a point lies within them:
$polygon = GeoJSON::fromJson($geofenceGeoJson);
$point = new \Cowegis\GeoJSON\Point([102.0, 0.5]);
// Note: Library doesn't support spatial queries; use PostGIS or frontend JS for this.
Batch Processing Validate/transform GeoJSON in bulk:
$features = collect($rawGeoJsonArray)->map(function ($feature) {
if (!GeoJSON::isValid($feature)) {
throw new \RuntimeException("Invalid GeoJSON in batch.");
}
return GeoJSON::fromJson($feature);
});
Event-Driven GeoJSON Trigger actions on GeoJSON changes (e.g., geofence events):
// Example: Listen for GeoJSON updates in a model observer
Location::observe(LocationObserver::class);
// app/Observers/LocationObserver.php
public function saved(Location $location)
{
if ($location->wasChanged('coordinates')) {
$geoJson = GeoJSON::encode($location->coordinates);
// Dispatch event or notify frontend via Laravel Echo
}
}
geometry for advanced queries:
$geoJson = GeoJSON::encode($feature);
$geometry = DB::select("ST_GeomFromGeoJSON(?)", [$geoJson]);
public function test_geojson_validation()
{
$this->assertTrue(GeoJSON::isValid('{"type":"Point","coordinates":[0,0]}'));
$this->assertFalse(GeoJSON::isValid('invalid json'));
}
PHP 8.2+ Requirement
Strict RFC 7946 Compliance
No Spatial Operations
Large GeoJSON Payloads
GPL-3.0 License
Validation Errors
GeoJSON::validate() to get detailed error messages:
$errors = GeoJSON::validate($geoJsonString);
// $errors contains an array of validation issues.
Serialization Issues
JsonSerializable correctly. For custom properties, extend the base classes:
class CustomFeature extends \Cowegis\GeoJSON\Feature
{
public function jsonSerialize()
{
$data = parent::jsonSerialize();
$data['custom_property'] = $this->customProperty;
return $data;
}
}
Database Storage
jsonb is ideal for GeoJSON, but MySQL’s json type lacks geospatial indexing. Use geometry columns in PostGIS instead:
// Migration for PostGIS
Schema::create('locations', function (Blueprint $table) {
$table->id();
$table->geometry('coordinates'); // PostGIS geometry column
$table->timestamps();
});
Default Coordinate Order
[longitude, latitude] by default (RFC 7946 compliant). Ensure your data matches this order:
$point = new \Cowegis\GeoJSON\Point([102.0, 0.5]); // Correct
$point = new \Cowegis\GeoJSON\Point([0.5, 102.0]); // Incorrect (latitude, longitude)
FeatureCollection vs. Feature
Feature and FeatureCollection incorrectly can cause serialization errors. Always wrap multiple features in a FeatureCollection:
// Correct
$collection = new \Cowegis\GeoJSON\FeatureCollection([$feature1, $feature2]);
// Incorrect (will fail validation
How can I help you explore Laravel packages today?