Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cowegis Geojson Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cowegis/cowegis-geojson
    

    Verify PHP version meets the requirement (^8.2).

  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.");
    }
    
  3. Where to Look First

    • Core Classes: Focus on GeoJSON (static methods for validation/parsing) and geometry classes (Point, LineString, Polygon, etc.).
    • Documentation: Prioritize the RFC 7946 spec for edge cases not covered by the library.
    • Laravel Integration: Start with JsonSerializable for Eloquent models and request validation.

Implementation Patterns

Usage Patterns

  1. 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);
            }],
        ];
    }
    
  2. 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
    
  3. 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,
        ];
    }
    
  4. 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();
    
  5. Frontend Integration Ensure outputs are compatible with JavaScript libraries:

    // Return GeoJSON for Leaflet/Mapbox
    return response()->json([
        'type' => 'FeatureCollection',
        'features' => GeoJSON::encode($features),
    ]);
    

Workflows

  1. 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.
    
  2. 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);
    });
    
  3. 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
        }
    }
    

Integration Tips

  • Laravel Scout: Use the library to index geospatial data in search engines like Algolia (if they support GeoJSON).
  • PostGIS: Convert GeoJSON to PostGIS geometry for advanced queries:
    $geoJson = GeoJSON::encode($feature);
    $geometry = DB::select("ST_GeomFromGeoJSON(?)", [$geoJson]);
    
  • Testing: Write feature tests for GeoJSON validation/serialization:
    public function test_geojson_validation()
    {
        $this->assertTrue(GeoJSON::isValid('{"type":"Point","coordinates":[0,0]}'));
        $this->assertFalse(GeoJSON::isValid('invalid json'));
    }
    

Gotchas and Tips

Pitfalls

  1. PHP 8.2+ Requirement

    • Issue: May conflict with older Laravel versions or shared hosting.
    • Fix: Use a PHP polyfill or upgrade your environment.
  2. Strict RFC 7946 Compliance

    • Issue: The library enforces strict GeoJSON validation, which may reject "loose" GeoJSON from third-party sources.
    • Fix: Pre-process data or use a lenient parser if needed (though this package doesn’t support it).
  3. No Spatial Operations

    • Issue: The library cannot perform geospatial calculations (e.g., distance, intersection). These require PostGIS or frontend JS.
    • Fix: Offload spatial logic to the database or use libraries like turf/turf on the frontend.
  4. Large GeoJSON Payloads

    • Issue: Processing large GeoJSON objects (e.g., FeatureCollections with thousands of features) may hit memory limits.
    • Fix: Stream processing or chunk data into smaller batches.
  5. GPL-3.0 License

    • Issue: May conflict with proprietary codebases or other GPL-incompatible dependencies.
    • Fix: Review license compatibility with your legal team or consider alternatives like spatie/geo (MIT-licensed).

Debugging

  1. Validation Errors

    • Use GeoJSON::validate() to get detailed error messages:
      $errors = GeoJSON::validate($geoJsonString);
      // $errors contains an array of validation issues.
      
  2. Serialization Issues

    • Ensure all GeoJSON objects implement 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;
          }
      }
      
  3. Database Storage

    • PostgreSQL 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();
      });
      

Config Quirks

  1. Default Coordinate Order

    • The library expects [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)
      
  2. FeatureCollection vs. Feature

    • Mixing 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
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor