Skip to the content.

Collection of Google Maps API Web Services for Laravel

Provides a convenient way of setting up and making requests to Google Maps APIs from your Laravel application.

For services documentation, API key usage limits, and terms of service, please refer to the official Google Maps documentation:


Important Update: Routes API replaces Directions & Distance Matrix

The Google Maps Directions API and Distance Matrix API are deprecated.

This package now includes support for the new Google Maps Routes API, which is the recommended replacement for calculating routes and route matrices. The Routes API offers enhanced features and performance.

Please update your application code to use the routes and routematrix services provided by this package instead of the deprecated directions and distancematrix services.


Features

This package provides easy access to the following Google Maps APIs:


Dependency

API Deprecation Notes

In addition to the Directions and Distance Matrix deprecation mentioned above:

Places API:


Installation

Issue following command in console:

composer require alexpechkarev/google-maps

Configuration

Register Service Provider & Facade (in config/app.php):

'providers' => [
    ...
    GoogleMaps\ServiceProvider\GoogleMapsServiceProvider::class,
]

'aliases' => [
    ...
    'GoogleMaps' => GoogleMaps\Facade\GoogleMapsFacade::class,
]

Publish configuration file:

php artisan vendor:publish --tag=googlemaps

Add API Key: Open config/googlemaps.php* and add your Google Maps API key:

/*
|----------------------------------
| Service Keys
|------------------------------------
*/

'key'       => 'ADD YOUR SERVICE KEY HERE',

If you like to use different keys for any of the services, you can overwrite master API Key by specifying it in the service array for selected web service.

Usage

General Pattern: Load the desired service using \GoogleMaps::load('service-name'). Set parameters using setParam([...]) or setParamByKey('key', 'value'). Execute the request:

Example: Geocoding API (using get()):

$response = \GoogleMaps::load('geocoding')
		->setParam (['address' =>'santa cruz'])
 		->get();

By default, where appropriate, output parameter set to JSON. Don’t forget to decode JSON string into PHP variable.

Example: Routes API - Compute Route (using fetch()):

Note: The Routes API uses the fetch() method and returns a PHP array directly (no JSON decoding needed). Note: The config for routes includes a decodePolyline parameter (default true), which adds a decodedPolyline key to the response if a polyline is present.

$routeParams = [
    'origin' => [ /* ... origin details ... */ ],
    'destination' => [ /* ... destination details ... */ ],
    'travelMode' => 'DRIVE',
    // ... other Routes API parameters ...
];

$responseArray = \GoogleMaps::load('routes') // Use 'routes' service
    ->setParam($routeParams)
    ->setFieldMask('routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline') // optional - used to specify fields to return 
    ->fetch(); // Use fetch() for Routes API

// $responseArray is already a PHP array
if (!empty($responseArray['routes'])) {
    // Process the route data
} else {
    // Handle errors or no routes found
}

Example: Routes API - Compute Route Matrix (using fetch()):

$matrixParams = [
    'origins' => [ /* ... array of origins ... */ ],
    'destinations' => [ /* ... array of destinations ... */ ],
    'travelMode' => 'DRIVE',
    // ... other Route Matrix parameters ...
];

$responseArray = \GoogleMaps::load('routematrix') // Use 'routematrix' service
    ->setParam($matrixParams)
    ->setFieldMask('originIndex,destinationIndex,duration,distanceMeters,status,condition') // optional - used to specify fields to return 
    ->fetch(); // Use fetch() for Routes API

// $responseArray is already a PHP array
// Process the matrix data

Required parameters can be specified as an array of key:value pairs

$response = \GoogleMaps::load('geocoding')
		->setParam ([
		    'address'    =>'santa cruz',
            'components' => [
                    'administrative_area'  => 'TX',
                    'country'              => 'US',
                    ]
                ])
                ->get();

Alternatively parameters can be set using setParamByKey() method. For deeply nested array use “dot” notation as per example below.

$endpoint = \GoogleMaps::load('geocoding')
   ->setParamByKey('address', 'santa cruz')
   ->setParamByKey('components.administrative_area', 'TX') //return $this
    ...

Available methods


load( $serviceName ) - load web service by name

Accepts string as parameter, web service name as specified in configuration file. Returns reference to it’s self.

\GoogleMaps::load('geocoding')
...

setEndpoint( $endpoint ) - set request output

Accepts string as parameter, json or xml, if omitted defaulted to json. Returns reference to it’s self.

$response = \GoogleMaps::load('geocoding')
		->setEndpoint('json')  // return $this
		...

getEndpoint() - get current request output

Returns string.

$endpoint = \GoogleMaps::load('geocoding')
		->setEndpoint('json')
		->getEndpoint();

echo $endpoint; // output 'json'

setParamByKey( $key, $value ) - set request parameter using key:value pair

Accepts two parameters:

Deeply nested array can use ‘dot’ notation to assign value. Returns reference to it’s self.

$endpoint = \GoogleMaps::load('geocoding')
   ->setParamByKey('address', 'santa cruz')
   ->setParamByKey('components.administrative_area', 'TX') //return $this
    ...

setParam( $parameters) - set all request parameters at once

Accepts array of parameters Returns reference to it’s self.

$response = \GoogleMaps::load('geocoding')
                ->setParam([
                   'address'     => 'santa cruz',
                   'components'  => [
                        'administrative_area'   => 'TX',
                        'country'               => 'US',
                         ]
                     ]) // return $this
...

This method is not Available for Routes API.

Returns web service response in the format specified by setEndpoint() method, if omitted defaulted to JSON. Use json_decode() to convert JSON string into PHP variable. See Processing Response for more details on parsing returning output.

$response = \GoogleMaps::load('geocoding')
                ->setParamByKey('address', 'santa cruz')
                ->setParamByKey('components.administrative_area', 'TX')
                 ->get();

var_dump( json_decode( $response ) );  // output

/*
{\n
   "results" : [\n
      {\n
         "address_components" : [\n
            {\n
               "long_name" : "277",\n
               "short_name" : "277",\n
               "types" : [ "street_number" ]\n
            },\n
            ...
*/

Example with $key parameter

$response = \GoogleMaps::load('geocoding')
                ->setParamByKey('latlng', '40.714224,-73.961452')
                 ->get('results.formatted_address');

var_dump( json_decode( $response ) );  // output

/*
array:1 [▼
  "results" => array:9 [▼
    0 => array:1 [▼
      "formatted_address" => "277 Bedford Ave, Brooklyn, NY 11211, USA"
    ]
    1 => array:1 [▼
      "formatted_address" => "Grand St/Bedford Av, Brooklyn, NY 11211, USA"
    ]
            ...
*/

This method is ONLY available for Routes API. Note: config for routes included decodePolyline parameter, default true. If true it will attempts to decode the polilyne.encodedPolyline and add decodePolyline parameter to the response.

Returns an array web service response or thows an ErrorException. See Request Body for details.

$response = \GoogleMaps::load('routes')
                ->setParam($reqRoute) // <-- array see config file for all available parameters or Request Body
                ->fetch();

isLocationOnEdge( $lat, $lng, $tolrance = 0.1 ) - To determine whether a point falls on or near a polyline, or on or near the edge of a polygon, pass the point, the polyline/polygon, and optionally a tolerance value in degrees.

This method only available with Google Maps Routes API.

Accepted parameter:

$response = \GoogleMaps::load('routes')
            ->setParam([
                        'origin' => [
                            'location' => [
                                'latLng' => [
                                    'latitude' => 37.419734,
                                    'longitude' => -122.0827784,
                                ],
                            ],
                        ],
                        'destination' => [
                            'location' => [
                                'latLng' => [
                                    'latitude' => 37.417670,
                                    'longitude' => -122.079595,
                                ],
                            ],
                        ],
                        'travelMode' => 'DRIVE',
                        'routingPreference' => 'TRAFFIC_AWARE',
                        'computeAlternativeRoutes' => false,
                        'routeModifiers' => [
                            'avoidTolls' => false,
                            'avoidHighways' => false,
                            'avoidFerries' => false,
                        ],
                        'languageCode' => 'en-US',
                        'units' => 'IMPERIAL',
                    ])
           ->isLocationOnEdge(37.41665,-122.08175);

    dd( $response  );  // true

containsLocation( $lat, $lng ) -To find whether a given point falls within a polygon.

This method only available with Google Maps Routes API.

Accepted parameter:

$response = \GoogleMaps::load('routes')
            ->setParam([
                        'origin' => [
                            'location' => [
                                'latLng' => [
                                    'latitude' => 37.419734,
                                    'longitude' => -122.0827784,
                                ],
                            ],
                        ],
                        'destination' => [
                            'location' => [
                                'latLng' => [
                                    'latitude' => 37.417670,
                                    'longitude' => -122.079595,
                                ],
                            ],
                        ],
                        'travelMode' => 'DRIVE',
                        'routingPreference' => 'TRAFFIC_AWARE',
                        'computeAlternativeRoutes' => false,
                        'routeModifiers' => [
                            'avoidTolls' => false,
                            'avoidHighways' => false,
                            'avoidFerries' => false,
                        ],
                        'languageCode' => 'en-US',
                        'units' => 'IMPERIAL',
                    ])
           ->containsLocation(37.41764,-122.08293);

    dd( $response  );  // true

Support

Please open an issue on GitHub

License

Collection of Google Maps API Web Services for Laravel is released under the MIT License. See the bundled LICENSE file for details.