alexpechkarev/google-maps

repository·master·Indexed 20 days ago

https://github.com/alexpechkarev/google-maps

A Laravel-specific wrapper for Google Maps API Web Services providing a fluent interface for interacting with endpoints including the Routes API (replacing Directions and Distance Matrix), Elevation, Geocoding, Geolocation, Roads, Time Zone, and Places API Web Services. It features a GoogleMaps facade, support for dot notation in parameters, and spatial analysis tools like containsLocation and isLocationOnEdge for route geometry.

Tokens
5.2K
Snippets
28
Records
29
Agent score
68%

What's inside alexpechkarev/google-maps

  1. How to use the Google Maps package (General Pattern)

    master

    The package follows a consistent pattern for making requests:

    1. Load a service: Use \GoogleMaps::load('service-name').
    2. Set parameters: Use setParam([...]) for arrays or setParamByKey('key', 'value') for single values. For nested arrays, use dot notation (e.g., components.country).
    3. Execute the request:
      • Use ->get() for most APIs (Geocoding, Elevation, etc.). Note that get() returns a JSON string that you must decode into a PHP variable.
      • Use ->fetch() ONLY for the Routes API (routes and routematrix services). fetch() returns a PHP array directly.
    // Standard API pattern
    $response = \GoogleMaps::load('geocoding')
        ->setParam(['address' => 'santa cruz'])
        ->get();
    
    // Routes API pattern
    $response = \GoogleMaps::load('routes')
        ->setParam($params)
        ->fetch();
  2. Configure your Google Maps API Key

    master
    1. Publish the configuration file using Artisan:
      php artisan vendor:publish --tag=googlemaps
    2. Open config/googlemaps.php and add your API key to the key field.

    You can also specify unique keys for specific services by overwriting the master key within the service array in the config file.

    'key' => 'ADD YOUR SERVICE KEY HERE',
  3. Configure the Google Maps Service Provider and Facade

    master

    To use the GoogleMaps facade, register the Service Provider and the Facade alias in your config/app.php file.

    'providers' => [
        ...
        GoogleMaps\ServiceProvider\GoogleMapsServiceProvider::class,
    ]
    
    'aliases' => [
        ...
        'GoogleMaps' => GoogleMaps\Facade\GoogleMapsFacade::class,
    ]
  4. Set parameters using dot notation

    master

    When using setParamByKey(), you can set deeply nested array values using dot notation.

    $endpoint = \GoogleMaps::load('geocoding')
       ->setParamByKey('address', 'santa cruz')
       ->setParamByKey('components.administrative_area', 'TX');
  5. Execute requests for the Routes API

    master

    For the Routes API (routes and routematrix services), use the fetch() method instead of get().

    • fetch(): Executes the request and returns a decoded PHP array directly. It throws an ErrorException if the request fails.
    • Polyline Decoding: The Routes API configuration includes a decodePolyline parameter which defaults to true. When enabled, the service attempts to decode polyline.encodedPolyline and adds the decodePolyline parameter to the response.
    $response = \GoogleMaps::load('routes')
                    ->setParam($reqRoute) // $reqRoute is an array of parameters from the Routes API spec
                    ->fetch();
  6. Configure request output format

    master

    Use setEndpoint( $endpoint ) to specify the desired response format. Supported values are 'json' (default) or 'xml'.

    Note: This method is not applicable to the Routes API when using fetch().

    $response = \GoogleMaps::load('geocoding')
    	->setEndpoint('json'); // returns $this
  7. Set request parameters

    master

    You can set request parameters using either a single key-value pair or an entire array of parameters.

    • setParamByKey( $key, $value ): Sets a single parameter. You can use 'dot' notation for deeply nested arrays (e.g., 'components.country').
    • setParam( $parameters ): Sets multiple parameters at once using an associative array.
    // Using setParamByKey with dot notation
    $endpoint = \GoogleMaps::load('geocoding')
       ->setParamByKey('address', 'santa cruz')
       ->setParamByKey('components.administrative_area', 'TX');
    
    // Using setParam with an array
    $response = \GoogleMaps::load('geocoding')
                    ->setParam([
                       'address'     => 'santa cruz',
                       'components'  => [
                            'administrative_area'   => 'TX',
                            'country'               => 'US',
                         ]
                     ]);
  8. Spatial analysis with Routes API

    master

    The Routes API provides methods to perform spatial checks against the returned route geometry. These methods require a prior setParam() call to define the route.

    • containsLocation( $lat, $lng ): Returns true if the provided latitude and longitude fall within the polygon returned by the route.
    • isLocationOnEdge( $lat, $lng, $tolerance ): Returns true if the point falls on or near the polyline/polygon. The $tolerance parameter (defaulting to 0.1) allows you to define how close the point must be to the edge to be considered 'on' it.
    // Check if a point is on the edge of a route
    $isOnEdge = \GoogleMaps::load('routes')
                ->setParam($routeParams)
                ->isLocationOnEdge(37.41665, -122.08175);
    
    // Check if a point is inside the route polygon
    $isInside = \GoogleMaps::load('routes')
                ->setParam($routeParams)
                ->containsLocation(37.41764, -122.08293);
  9. Use the Routes API to compute a route matrix

    master

    The routematrix service is the recommended replacement for the deprecated Distance Matrix API. Like the routes service, it uses fetch() and returns a PHP array directly.

    $matrixParams = [
        'origins' => [ /* ... array of origins ... */ ],
        'destinations' => [ /* ... array of destinations ... */ ],
        'travelMode' => 'DRIVE',
    ];
    
    $responseArray = \GoogleMaps::load('routematrix')
        ->setParam($matrixParams)
        ->setFieldMask('originIndex,destinationIndex,duration,distanceMeters,status,condition')
        ->fetch();
  10. Load a Google Maps web service

    master

    Use load( $serviceName ) to initialize a specific web service configuration. The $serviceName must match a service name defined in your configuration file (e.g., 'geocoding', 'routes', or 'routematrix'). This method returns $this to allow for method chaining.

    \GoogleMaps::load('geocoding');