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

Geodata Laravel Package

arsenyru/geodata

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require arsenyru/geodata
    

    Note: Requires Symfony 2.3+ (not Laravel-compatible natively; see Integration Patterns for Laravel adaptation).

  2. First Use Case:

    • Convert Coordinates: Use the Geodata\Coordinate\Coordinate class to handle lat/long conversions.
      use Geodata\Coordinate\Coordinate;
      
      $coordinate = new Coordinate(55.7558, 37.6173); // Moscow
      $formatted = $coordinate->toString(); // "55.7558, 37.6173"
      
  3. Key Classes to Explore:

    • Geodata\Coordinate\Coordinate: Core class for lat/long operations.
    • Geodata\Distance\Distance: Calculate distances between coordinates.
    • Geodata\GeoJson\GeoJson: Work with GeoJSON-formatted data.

Implementation Patterns

Laravel Integration

  1. Service Provider: Register the package as a Laravel service provider (e.g., GeodataServiceProvider):

    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Geodata\Coordinate\Coordinate;
    
    class GeodataServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton('geodata.coordinate', function ($app) {
                return new Coordinate(...); // Inject defaults if needed
            });
        }
    }
    
  2. Facade (Optional): Create a facade for cleaner syntax:

    // app/Facades/Geodata.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class Geodata extends Facade
    {
        protected static function getFacadeAccessor() { return 'geodata.coordinate'; }
    }
    

    Usage:

    $distance = app('geodata.coordinate')->distanceTo(new Coordinate(...));
    
  3. Request/Response Handling:

    • Parse lat/long from request input:
      $lat = request()->input('lat');
      $lng = request()->input('lng');
      $coordinate = new Coordinate($lat, $lng);
      
    • Return GeoJSON in API responses:
      return response()->json([
          'data' => (new GeoJson())->createPoint($coordinate)
      ]);
      
  4. Model Bindings: Bind coordinates to Eloquent models:

    use Geodata\Coordinate\Coordinate;
    
    class Location extends Model
    {
        protected $casts = [
            'coordinates' => 'array',
        ];
    
        public function getCoordinateAttribute()
        {
            return new Coordinate($this->latitude, $this->longitude);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependency:

    • The package is Symfony 2.x-specific (e.g., uses Symfony\Component\Form). Laravel users must mock or abstract Symfony dependencies.
    • Workaround: Use a wrapper class to isolate Symfony-specific logic.
  2. TCPDF Requirement:

    • The package requires tecnick.com/tcpdf for PDF generation (unused in most Laravel apps). Exclude it via:
      composer require arsenyru/geodata --ignore-platform-req=tecnick.com/tcpdf
      
  3. Coordinate Validation:

    • Latitude/longitude values must be validated manually (no built-in validation):
      if (!$coordinate->isValid()) {
          throw new \InvalidArgumentException("Invalid coordinates");
      }
      
  4. GeoJSON Limitations:

    • The GeoJson class lacks Laravel-specific features (e.g., no database integration). Extend it for custom needs:
      class LaravelGeoJson extends \Geodata\GeoJson\GeoJson
      {
          public function toDatabaseArray()
          {
              return $this->toArray(); // Custom serialization
          }
      }
      

Debugging Tips

  1. Coordinate Precision:

    • Default precision is 6 decimal places. Adjust via:
      $coordinate = new Coordinate(55.7558, 37.6173, 4); // 4 decimal places
      
  2. Distance Units:

    • Distance calculations default to kilometers. Use Distance::MILES for miles:
      $distance = $coordinate->distanceTo($otherCoordinate, Distance::MILES);
      
  3. Performance:

    • Avoid instantiating Coordinate objects repeatedly. Cache or reuse instances:
      $cacheKey = "coord:{$lat}:{$lng}";
      $coordinate = cache()->remember($cacheKey, now()->addHours(1), fn() => new Coordinate($lat, $lng));
      

Extension Points

  1. Custom Distance Calculators:

    • Extend Geodata\Distance\Distance for alternative algorithms (e.g., Haversine):
      class HaversineDistance extends Distance
      {
          protected function calculate($lat1, $lon1, $lat2, $lon2)
          {
              // Custom Haversine formula
          }
      }
      
  2. Database Storage:

    • Store coordinates as a single POINT field in PostgreSQL:
      // Migration
      $table->geometry('location');
      
      // Model
      public function setCoordinatesAttribute($value)
      {
          $this->attributes['location'] = "POINT({$value->longitude} {$value->latitude})";
      }
      
  3. API Resources:

    • Use Laravel’s API Resources to format GeoJSON responses:
      namespace App\Http\Resources;
      
      use Illuminate\Http\Resources\Json\JsonResource;
      use Geodata\GeoJson\GeoJson;
      
      class LocationResource extends JsonResource
      {
          public function toArray($request)
          {
              return [
                  'geometry' => (new GeoJson())->createPoint($this->coordinate),
                  'properties' => $this->properties,
              ];
          }
      }
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle