PHPackages                             alexpechkarev/google-maps - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. alexpechkarev/google-maps

ActiveLibrary[API Development](/categories/api)

alexpechkarev/google-maps
=========================

Collection of Google Maps API Web Services for Laravel

v12.14(2mo ago)5653.2M↑17.5%117[1 issues](https://github.com/alexpechkarev/google-maps/issues)2MITPHP

Since Sep 3Pushed 2mo ago27 watchersCompare

[ Source](https://github.com/alexpechkarev/google-maps)[ Packagist](https://packagist.org/packages/alexpechkarev/google-maps)[ Docs](https://alexpechkarev.github.io/google-maps/)[ RSS](/packages/alexpechkarev-google-maps/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (40)Used By (2)

Collection of Google Maps API Web Services for Laravel
------------------------------------------------------

[](#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](http://laravel.com/) application.

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

- [Google Maps API Web Services](https://developers.google.com/maps/documentation/webservices/)
- [Maps API Terms of Service &amp; License Restrictions](https://developers.google.com/maps/terms#section_10_12).

---

### Important Update: Routes API replaces Directions &amp; Distance Matrix

[](#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
--------

[](#features)

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

- **[Routes API](https://developers.google.com/maps/documentation/routes/route-usecases) (Recommended replacement for Directions &amp; Distance Matrix)**
    - `routes`: Compute routes between locations.
    - `routematrix`: Compute route matrices between origins and destinations.
- [Elevation API](https://developers.google.com/maps/documentation/elevation/)
- [Geocoding API](https://developers.google.com/maps/documentation/geocoding/)
- [Geolocation API](https://developers.google.com/maps/documentation/geolocation/)
- [Roads API](https://developers.google.com/maps/documentation/roads/)
- [Time Zone API](https://developers.google.com/maps/documentation/timezone/)
- [Places API Web Services](https://developers.google.com/places/web-service/)

---

Dependency
----------

[](#dependency)

- [PHP cURL](http://php.net/manual/en/curl.installation.php)
- [PHP &gt;= 7.3.0](http://php.net/)

API Deprecation Notes
---------------------

[](#api-deprecation-notes)

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

**Places API:**

- **Removed Features:** Requests attempting to use Place Add, Place Delete, or Radar Search will receive an error. [More Info](https://cloud.google.com/blog/products/maps-platform/announcing-deprecation-of-place-add)
- **Deprecated Parameters/Fields:**
    - Nearby Search: The `types` parameter is deprecated; use the `type` parameter (string) instead.
    - Place Details: The `reference` field is deprecated; use `placeid` (this package uses `placeid` by default).
    - Place Add &amp; Place Autocomplete: Still use the `types` parameter as per Google's documentation (links provided in the original README).

---

Installation
------------

[](#installation)

Issue following command in console:

```
composer require alexpechkarev/google-maps
```

Configuration
-------------

[](#configuration)

Register Service Provider &amp; 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
-----

[](#usage)

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

- Use `->get()` for all APIs EXCEPT the Routes API.
- Use `->fetch()` ONLY for the Routes API (routes and routematrix services).

#### Example: Geocoding API (using `get()`):

[](#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()`):

[](#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()`):

[](#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
-----------------

[](#available-methods)

- [`load( $serviceName )`](#load): Loads the specified web service configuration. Returns $this.
- [`setEndpoint( $endpoint )`](#setEndpoint): Sets the desired response format (json or xml) for APIs using get(). Default is json. Not applicable to Routes API (fetch()). Returns $this.
- [`getEndpoint()`](#getEndpoint): Gets the currently configured endpoint format (json or xml).
- [`setParamByKey( $key, $value)`](#setParamByKey): Sets a single request parameter. Use 'dot' notation for nested arrays (e.g., components.country). Returns $this.
- [`setParam( $parameters)`](#setParam): Sets multiple request parameters from an array. Returns $this.
- [`get()`](#get): (**For all APIs EXCEPT Routes API**) Executes the request. Returns a JSON string (or XML string if configured). If $key is provided (using 'dot' notation), attempts to return only that part of the response.
- [`fetch()`](#fetch): (**ONLY for Routes API** - `routes` and `routematrix`) Executes the request against the Routes API. Returns a decoded PHP array directly or throws an `ErrorException`.
- [`containsLocation( $lat, $lng )`](#containsLocation): (**Routes API only**) Checks if a point falls within the polygon returned by a routes API call. Requires a prior `setParam()` call for the route. Returns boolean.
- [`isLocationOnEdge( $lat, $lng, $tolrance)`](#isLocationOnEdge): (**Routes API only**) Checks if a point falls on or near the polyline returned by a routes API call. Requires a prior `setParam()` call for the route. Returns boolean.

---

**`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:

- `key` - body parameter name
- `value` - body parameter value

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
...
```

---

- **`get()`** - perform web service request (irrespectively to request type POST or GET )
- **`get( $key )`** - accepts string response body key, use 'dot' notation for deeply nested array

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](https://developers.google.com/maps/documentation/webservices/#Parsing) 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"
    ]
            ...
*/
```

---

- **`fetch()`** - only available for Routes API (whith 'routes' or 'routematrix' services)

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](https://developers.google.com/maps/documentation/routes/reference/rest/v2/TopLevel/computeRoutes#request-body) for details.

```
$response = \GoogleMaps::load('routes')
                ->setParam($reqRoute) // 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:

- `$lat` - double latitude
- `$lng` - double longitude
- `$tolrance` - double

```
$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:

- `$lat` - double latitude
- `$lng` - double longitude

```
$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
-------

[](#support)

[Please open an issue on GitHub](https://github.com/alexpechkarev/google-maps/issues)

License
-------

[](#license)

Collection of Google Maps API Web Services for Laravel is released under the MIT License. See the bundled [LICENSE](https://github.com/alexpechkarev/google-maps/blob/master/LICENSE)file for details.

###  Health Score

69

—

FairBetter than 100% of packages

Maintenance87

Actively maintained with recent releases

Popularity65

Solid adoption and visibility

Community35

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor1

Top contributor holds 77.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~104 days

Recently: every ~88 days

Total

38

Last Release

64d ago

Major Versions

7.1 → 8.02020-09-13

5.8.x-dev → 9.02022-02-13

9.0 → v10.0.12023-02-19

v10.0.2 → v11.0.02024-03-22

v11.0.0 → v12.0.02025-03-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/1cc8e1ca17a8158b131c60f92d5c5243073bfa762fb34b9263c0fbc15f072132?d=identicon)[alexpechkarev](/maintainers/alexpechkarev)

---

Top Contributors

[![alexpechkarev](https://avatars.githubusercontent.com/u/5559162?v=4)](https://github.com/alexpechkarev "alexpechkarev (142 commits)")[![markwalet](https://avatars.githubusercontent.com/u/11446771?v=4)](https://github.com/markwalet "markwalet (12 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (4 commits)")[![fa2mm](https://avatars.githubusercontent.com/u/3799461?v=4)](https://github.com/fa2mm "fa2mm (3 commits)")[![bardiauto](https://avatars.githubusercontent.com/u/73226167?v=4)](https://github.com/bardiauto "bardiauto (3 commits)")[![parkourben99](https://avatars.githubusercontent.com/u/7295774?v=4)](https://github.com/parkourben99 "parkourben99 (2 commits)")[![repat](https://avatars.githubusercontent.com/u/516807?v=4)](https://github.com/repat "repat (2 commits)")[![gart77](https://avatars.githubusercontent.com/u/13002423?v=4)](https://github.com/gart77 "gart77 (2 commits)")[![vesper8](https://avatars.githubusercontent.com/u/816028?v=4)](https://github.com/vesper8 "vesper8 (2 commits)")[![SDekkers](https://avatars.githubusercontent.com/u/913981?v=4)](https://github.com/SDekkers "SDekkers (1 commits)")[![Syrok](https://avatars.githubusercontent.com/u/124498?v=4)](https://github.com/Syrok "Syrok (1 commits)")[![xeader](https://avatars.githubusercontent.com/u/1153759?v=4)](https://github.com/xeader "xeader (1 commits)")[![brianrlewis](https://avatars.githubusercontent.com/u/31142584?v=4)](https://github.com/brianrlewis "brianrlewis (1 commits)")[![cyrillkalita](https://avatars.githubusercontent.com/u/2401848?v=4)](https://github.com/cyrillkalita "cyrillkalita (1 commits)")[![danswiser](https://avatars.githubusercontent.com/u/6931029?v=4)](https://github.com/danswiser "danswiser (1 commits)")[![dmhernandez2525](https://avatars.githubusercontent.com/u/47400105?v=4)](https://github.com/dmhernandez2525 "dmhernandez2525 (1 commits)")[![facundofarias](https://avatars.githubusercontent.com/u/2700564?v=4)](https://github.com/facundofarias "facundofarias (1 commits)")[![makhnovskiy](https://avatars.githubusercontent.com/u/3479205?v=4)](https://github.com/makhnovskiy "makhnovskiy (1 commits)")[![neoteknic](https://avatars.githubusercontent.com/u/1809652?v=4)](https://github.com/neoteknic "neoteknic (1 commits)")[![nmfzone](https://avatars.githubusercontent.com/u/10361906?v=4)](https://github.com/nmfzone "nmfzone (1 commits)")

---

Tags

google-mapslaravelphpGoogle Maps APIgeocoding apielevation apigeolocation apiroads apitime zone apiplaces api web servicegoogle maps api for laravelgoogle maps web service for laravellaravel google maps apiroutes api

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/alexpechkarev-google-maps/health.svg)

```
[![Health](https://phpackages.com/badges/alexpechkarev-google-maps/health.svg)](https://phpackages.com/packages/alexpechkarev-google-maps)
```

###  Alternatives

[andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API

1.0k586.2k3](/packages/andreaselia-laravel-api-to-postman)[dymantic/laravel-instagram-feed

Fetches the instagram feed for given authenticated profiles

151157.7k](/packages/dymantic-laravel-instagram-feed)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[ivanwilliammd/satusehat-integration

Build SATUSEHAT FHIR Object in Easy Way

754.0k](/packages/ivanwilliammd-satusehat-integration)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
