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

Php Shapefile Laravel Package

gasparesganga/php-shapefile

Read and write ESRI Shapefiles in PHP with support for common geometry formats. php-shapefile handles SHP/SHX/DBF data, works with WKT and GeoJSON, and includes docs and examples for parsing, editing, and exporting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require gasparesganga/php-shapefile
    

    Add to composer.json if using Laravel's autoloader:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Shapefile\\": "vendor/gasparesganga/php-shapefile/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Read a shapefile:

    use Shapefile\ShapefileReader;
    
    $reader = new ShapefileReader('path/to/shapefile.shp');
    $record = $reader->fetchRecord(); // Fetch first record
    $geometry = $record->getGeometry(); // Get geometry object
    $properties = $record->getProperties(); // Get attributes
    

Implementation Patterns

Core Workflows

  1. Reading Shapefiles:

    $reader = new ShapefileReader('file.shp', [
        Shapefile::OPTION_DBF_CONVERT_TO_UTF8 => true,
        Shapefile::OPTION_POLYGON_CLOSED_RINGS_ACTION => Shapefile::ACTION_FORCE,
    ]);
    
    while ($record = $reader->fetchRecord()) {
        $geom = $record->getGeometry();
        $props = $record->getProperties();
        // Process data
    }
    
  2. Writing Shapefiles:

    $writer = new ShapefileWriter('output.shp', [
        Shapefile::OPTION_BUFFERED_RECORDS => true,
        Shapefile::OPTION_EXISTING_FILES_MODE => Shapefile::MODE_OVERWRITE,
    ]);
    
    // Add fields
    $writer->addField('name', Shapefile::DBF_TYPE_CHAR, 50);
    $writer->addField('area', Shapefile::DBF_TYPE_FLOAT, 10, 2);
    
    // Add records
    $writer->addRecord([
        'name' => 'Region 1',
        'area' => 125.5,
        'geometry' => new Shapefile\Geometry\Polygon([...])
    ]);
    
  3. GeoJSON Conversion:

    $reader = new ShapefileReader('file.shp');
    $features = [];
    while ($record = $reader->fetchRecord()) {
        $features[] = $record->toGeoJSON();
    }
    
  4. WKT Conversion:

    $geom = new Shapefile\Geometry\Polygon([...]);
    $wkt = $geom->toWKT();
    

Integration Tips

  • Laravel Storage: Use Laravel's Storage facade to handle file paths:
    $path = storage_path('app/shapefiles/file.shp');
    $reader = new ShapefileReader($path);
    
  • Eloquent Models: Store shapefile data in a database and use the package for conversions:
    public function getGeoJsonAttribute()
    {
        $geom = new Shapefile\Geometry\Polygon($this->coordinates);
        return $geom->toGeoJSON();
    }
    
  • API Responses: Return GeoJSON directly from controllers:
    return response()->json($shapefile->toGeoJSON());
    
  • Batch Processing: Use Laravel's queues for large shapefiles:
    ShapefileProcessor::dispatch('large_file.shp')->onQueue('shapefiles');
    

Gotchas and Tips

Pitfalls

  1. File Corruption:

    • If a shapefile is corrupted (missing .shx or .dbf), use:
      $reader = new ShapefileReader('file.shp', [
          Shapefile::OPTION_IGNORE_FILE_DBF => true,
          Shapefile::OPTION_IGNORE_FILE_SHX => true,
      ]);
      
    • Tip: Always validate files before processing:
      try {
          $reader = new ShapefileReader('file.shp');
      } catch (ShapefileException $e) {
          Log::error("Shapefile error: " . $e->getMessage());
      }
      
  2. Polygon Orientation:

    • By default, polygons are counter-clockwise (OGC standard). To enforce clockwise:
      $polygon = new Shapefile\Geometry\Polygon([...], [
          'force_orientation' => Shapefile::ORIENTATION_CLOCKWISE,
      ]);
      
    • Gotcha: ESRI Shapefiles use clockwise orientation by default. Use forceCounterClockwise() if converting to OGC-compliant formats.
  3. Field Name Sanitization:

    • Field names are sanitized to avoid conflicts. To preserve original names:
      $writer->addField('Field Name', Shapefile::DBF_TYPE_CHAR, 50, null, null, true);
      
    • Tip: Use Shapefile::OPTION_DBF_FORCE_ALL_CAPS for consistency:
      $writer = new ShapefileWriter('file.shp', [
          Shapefile::OPTION_DBF_FORCE_ALL_CAPS => true,
      ]);
      
  4. Performance:

    • For large shapefiles, enable buffering:
      $writer = new ShapefileWriter('file.shp', [
          Shapefile::OPTION_BUFFERED_RECORDS => true,
      ]);
      
    • Tip: Call flushBuffer() periodically to reduce memory usage:
      $writer->flushBuffer();
      
  5. Coordinate Systems:

    • The package does not handle projections. Use libraries like php-proj or geosphp for transformations:
      // Example with geosphp
      $geom = new Shapefile\Geometry\Polygon([...]);
      $wkt = $geom->toWKT();
      $transformed = Proj::transform($wkt, 'EPSG:4326', 'EPSG:3857');
      
  6. Empty Shapefiles:

    • If a shapefile has no records, getTotRecords() returns Shapefile::UNKNOWN. Handle this case:
      if ($reader->getTotRecords() === Shapefile::UNKNOWN) {
          // Handle empty shapefile
      }
      
  7. DBF Field Limits:

    • DBF files have a 255-field limit. To bypass this:
      $writer = new ShapefileWriter('file.shp', [
          Shapefile::OPTION_DBF_ALLOW_FIELD_SIZE_255 => true,
      ]);
      

Debugging

  1. Enable Detailed Errors:

    try {
        $reader = new ShapefileReader('file.shp');
    } catch (ShapefileException $e) {
        Log::error("Error details: " . $e->getDetails());
    }
    
  2. Check Geometry Validity:

    • Use isValid() on geometry objects:
      if (!$polygon->isValid()) {
          $polygon->forceClosedRings();
      }
      
  3. Validate GeoJSON:

    • Use Laravel's json_validate helper or a library like geojson-php to validate GeoJSON output.

Extension Points

  1. Custom Geometry Classes:

    • Extend Shapefile\Geometry classes to add domain-specific logic:
      class CustomPolygon extends Shapefile\Geometry\Polygon {
          public function calculateCustomArea() {
              // Custom logic
          }
      }
      
  2. Override Field Encoding:

    • Extend ShapefileWriter to customize field encoding:
      class CustomWriter extends ShapefileWriter {
          protected function encodeFieldValue($value, $type, $size, $decimals) {
              // Custom encoding logic
          }
      }
      
  3. Add Validation:

    • Use Laravel's validation rules for shapefile attributes:
      $validator = Validator::make($properties, [
          'name' => 'required|string|max:50',
          'area' => 'required|numeric|min:0',
      ]);
      
  4. Event Listeners:

    • Dispatch events for shapefile operations (e.g., shapefile.record.processed):
      event(new ShapefileProcessed($record));
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui