Collection of Google Maps API Web Services for Laravel

Overview

Collection of Google Maps API Web Services for Laravel

Provides convenient way of setting up and making requests to Maps API from Laravel application. For services documentation, API key and Usage Limits visit Google Maps API Web Services and Maps API for Terms of Service License Restrictions.

Features

Dependency

Notes

Rmoving Place Add, Delete & Radar Search features

Requests to the Places API attempting to use these features will receive an error response

  • Place Add
  • Place Delete
  • Radar Search

Deprication notices for Google Places API Web Service that effects Premium data (Zagat), types parameter, id and reference fields.

  • Nearby Search - types parameter depricated, use parameter type (string)
  • Place Details - the reference is now deprecated in favor of placeid (placeid originally used in this package)
  • Place Add - still uses types parameter as per service documentation
  • Place Autocomplete - still uses types parameter as per service documentation

Installation

Issue following command in console:

For laravel 6 use 6.0.

composer require alexpechkarev/google-maps

Alternatively edit composer.json by adding following line and run composer update

"require": {
		....,
		"alexpechkarev/google-maps":"^8.0",

	},

Configuration

Register package service provider and facade in 'config/app.php'

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

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

Publish configuration file using php artisan vendor:publish --tag=googlemaps or simply copy package configuration file and paste into config/googlemaps.php

Open configuration file config/googlemaps.php and add your service 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

Here is an example of making request to Geocoding API:

$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. See Processing Response for more details on parsing returning output.

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

Another example showing request to Places API Place Add service:

$response = \GoogleMaps::load('placeadd')
                ->setParam([
                   'location' => [
                        'lat'  => -33.8669710,
                        'lng'  => 151.1958750
                      ],
                   'accuracy'           => 0,
                   "name"               =>  "Google Shoes!",
                   "address"            => "48 Pirrama Road, Pyrmont, NSW 2009, Australia",
                   "types"              => ["shoe_store"],
                   "website"            => "http://www.google.com.au/",
                   "language"           => "en-AU",
                   "phone_number"       =>  "(02) 9374 4000"
                          ])
                  ->get();

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:

  • 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

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"
    ]
            ...
*/

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 Directions API.

Accepted parameter:

  • $lat - double latitude
  • $lng - double longitude
  • $tolrance - double
$response = \GoogleMaps::load('directions')
            ->setParam([
                'origin'          => 'place_id:ChIJ685WIFYViEgRHlHvBbiD5nE',
                'destination'     => 'place_id:ChIJA01I-8YVhkgRGJb0fW4UX7Y',
            ])
           ->isLocationOnEdge(55.86483,-4.25161);

    dd( $response  );  // true

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

This method only available with Google Maps Directions API.

Accepted parameter:

  • $lat - double latitude
  • $lng - double longitude
$response = \GoogleMaps::load('directions')
            ->setParam([
                'origin'          => 'place_id:ChIJ685WIFYViEgRHlHvBbiD5nE',
                'destination'     => 'place_id:ChIJA01I-8YVhkgRGJb0fW4UX7Y',
            ])
           ->containsLocation(55.86483,-4.25161);

    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.

Comments
  • Address falls near another address using Lat/Long and Radius

    Address falls near another address using Lat/Long and Radius

    Hi,

    Actually, it's not an issue - but this is the only way I can contact you.

    Does this package support the following case:

    To check if an address falls within another address using Lat/Long and Radius.

    Thanks.

    opened by mansouralex 8
  • Decode Polyline point returned by Google Directions API

    Decode Polyline point returned by Google Directions API

    Hi I just installed your library and it looks pretty cool. Just wondering if there is any method to decode the polyline point returned in Directions response. Here is Directions API response:

    {
       "geocoded_waypoints" : [
          {
             "geocoder_status" : "OK",
             "place_id" : "ChIJlfTBINcEGTkR_Wu1RAUpDYI",
             "types" : [ "street_address" ]
          },
          {
             "geocoder_status" : "OK",
             "place_id" : "ChIJlfTBINcEGTkR_Wu1RAUpDYI",
             "types" : [ "street_address" ]
          }
       ],
       "routes" : [
          {
             "bounds" : {
                "northeast" : {
                   "lat" : 31.5562273,
                   "lng" : 74.3571711
                },
                "southwest" : {
                   "lat" : 31.55462439999999,
                   "lng" : 74.3546016
                }
             },
             "copyrights" : "Map data ©2015 Google",
             "legs" : [
                {
                   "distance" : {
                      "text" : "0.3 km",
                      "value" : 302
                   },
                   "duration" : {
                      "text" : "1 min",
                      "value" : 45
                   },
                   "end_address" : "132 Allama Iqbal Road, Lahore, Pakistan",
                   "end_location" : {
                      "lat" : 31.5562273,
                      "lng" : 74.3546016
                   },
                   "start_address" : "132 Allama Iqbal Road, Lahore, Pakistan",
                   "start_location" : {
                      "lat" : 31.55462439999999,
                      "lng" : 74.3571711
                   },
                   "steps" : [
                      {
                         "distance" : {
                            "text" : "0.3 km",
                            "value" : 302
                         },
                         "duration" : {
                            "text" : "1 min",
                            "value" : 45
                         },
                         "end_location" : {
                            "lat" : 31.5562273,
                            "lng" : 74.3546016
                         },
                         "html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e",
                         "polyline" : {
                            "points" : "k_r_Ei{ydM[r@e@bAOZWh@Ub@]p@c@`AU^e@p@cAxA"
                         },
                         "start_location" : {
                            "lat" : 31.55462439999999,
                            "lng" : 74.3571711
                         },
                         "travel_mode" : "DRIVING"
                      }
                   ],
                   "via_waypoint" : []
                }
             ],
             "overview_polyline" : {
                "points" : "k_r_Ei{ydMiB|Ds@tAy@`BiBjC" // this is the encoded polyline point to decode
             },
             "summary" : "Allama Iqbal Rd",
             "warnings" : [],
             "waypoint_order" : []
          }
       ],
       "status" : "OK"
    }
    

    I already decoded the point in JS, I need your help to do same using this library.

    Thanks

    opened by manzoor-ahmed 7
  • Update geometry-library to fix curly braces syntax error on 5.8 branch

    Update geometry-library to fix curly braces syntax error on 5.8 branch

    This fixes the "Array and string offset access syntax with curly braces is deprecated" on php >= 7.4 This can be useful for people using 5.8 branch with php version higher than 7.3. Please merge and create a tag.

    opened by zambodaniel 5
  • FatalErrorException in compiled.php line 5301:

    FatalErrorException in compiled.php line 5301:

    Hi,

    I'm currently working on a project that involves google maps turn by turn directions.

    I encounter this error, what could be the cause of this?

    Call to undefined method Illuminate\Support\Facades\GoogleMapsFacade::load()

    I placed the GoogleMapsFacade.php to Illuminate\Support\Facades\ directory.

    Thanks in advance.

    opened by cp-black 5
  • Php 7.2 incompatibility

    Php 7.2 incompatibility

    Have this exception running php 7.2 laravel 5.5

    ErrorException count(): Parameter must be an array or an object that implements Countable

    /vendor/alexpechkarev/google-maps/src/WebService.php:305

    
    // Validate Endpoint
    if(!array_key_exists('endpoint', config('googlemaps') )
            || !count(config('googlemaps.endpoint') < 1)){
        throw new \ErrorException('End point must not be empty.');
    }
    
    
    opened by m00n71ght 4
  • Optimize Waypoints in directions API not working properly

    Optimize Waypoints in directions API not working properly

    Setting the parameter optimizeWaypoints to true doesn't change the response.

    In the example from maps api documentation destinations are set this way: (...)waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA

    The curl request in this library adds the optimizeWaypoints=true to the end of the URL which doesn't return the array optimized_waypoints order correctly.

    opened by korolkovas 4
  • webservice:268 error

    webservice:268 error

    local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Can't use function return value in write context' in /var/www/'user'l/httpdocs/laravel/vendor/alexpechkarev/google-maps/src/WebService.php:268

    Hi i just started using laravel as framework and am almost done with my project with it. I have a problem with the google-maps. Everytime i try this code

    $response = \GoogleMaps::load('geocoding')->setParam (['address' =>'santa cruz'])->get(); I get the error thats written above. If you can please help me with this issue ill be really grateful.

    opened by tengju 4
  • Feature - add timeouts for curl

    Feature - add timeouts for curl

    This PR resolves the issue of timeouts when the google service is not responding in a reasonable time, this can cause high load on the server when handling many requests.

    Added a connection timeout with default 1 second and a request timeout with 5 seconds.

    opened by Lyimmi 3
  • Unable to find config file on controller

    Unable to find config file on controller

    I see your example on docs git directory, but you no have the "use GoogleMaps\Facade\GoogleMapsFacade;" in your controller.

    I try to use for add a map in my dashboard, but can't use because not understand how use in controller to return the map position and insert map on view.

    Thanks

    opened by ferrysoto 3
  • Array and string offset access syntax with curly braces is deprecated

    Array and string offset access syntax with curly braces is deprecated

    Hi alexpechkarev,

    I found that your library is very useful how ever there is an issue when use Direction api, i got following error,if you can please help me with that

    my PHP Version 7.4.2

    bandicam 2020-05-19 20-02-13-856

    error generating from this $b variable

    bandicam 2020-05-19 20-03-27-067

    Thank you

    opened by KasunAssetDidital 3
  • Get response

    Get response

    Hi, how can return multiples paramters? i need return name, photo, address, etc. i tried with this get('response.name.photo') get('response.['name.,photo']')

    but the response is all parameters.

    opened by cgalindez122 3
  • Expand

    Expand "jbroadway/urlify" version requirements?

    Just updated to the latest release for Laravel 9 — thanks for a great package!

    Whilst doing so, I noticed the jbroadway/urlify requirement in composer.json is ranged to ^1.1. This version causes Composer to throw an error when generating the autoloader due to PSR-0.

    I think the requirements should change to "jbroadway/urlify": "^1.1 | ^1.2", as the PSR-0 issue seems to have been fixed in 1.2.1.

    opened by JackWH 0
  • Ability to get more than 5 reviews

    Ability to get more than 5 reviews

    Hey,

    I'm fetching place details with the following code in laravel 8.

    $response =  GoogleMapsFacade::load('placedetails')->setParam([
        'place_id' => 'my_place_id'
    ])->get();
    

    This only seems to return 5 reviews, while the place has many more.

    Is it possible to get all reviews of a given place?

    opened by Donneh 0
  • How can I get the address information from a google link

    How can I get the address information from a google link

    hello , I have this google link -

    https://www.google.com.br/maps/@-22.4151458,-49.1328797,3a,75y,170.53h,82.38t/data=!3m6!1e1!3m4!1selNMIexYHQOrulrENDXAtg!2e0!7i13312!8i6656
    

    How can I get the address information ( latitude , longitude ..) , from a link like that ?

    opened by murilolivorato 0
  • Always get only one alternative Route

    Always get only one alternative Route

    Hi, I am trying to get all the alternative routes between two points with coordinates, but I always get only one route even though I am sending alternatives=true in the request parameters.

    Let me give you an example.

    In this link You will get three routes in total, the main route and two alternative routes. image

    But when I do it with your package I always get only one route. image

    This is the code I am using to get the alternate routes with your package.

    $origins = ['10.0631549', '-69.3103233'];
    $destinations = ['10.0540698', '-69.3421256'];
    
    $response = \GoogleMaps::load('directions')
                  ->setParam([
                      'origin' => implode(',', $origins),
                      'destination' => implode(',', $destinations),
                      'alternatives' => true,
                      'language' => 'es'
                  ])->get();
    

    What do I have to do to get the alternative routes with your package?

    opened by mreduar 1
Releases(9.0)
Owner
Alexander Pechkarev
Software Engineer and Web Systems Manager
Alexander Pechkarev
An easy way to integrate Google Maps with Laravel

An easy way to integrate Google Maps with Laravel For Laravel 5.x, check version 2.35.1 For Laravel 4.x, check version 1.27.0 Think of Googlmapper as

Bradley Cornford 450 Nov 29, 2022
A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDowell

PHPAlgorithms A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDow

Doğan Can Uçar 921 Dec 18, 2022
MapServer and PHP-MapScript application to create publication-quality maps

SimpleMappr Installation and Configuration SimpleMappr, http://www.simplemappr.net is a web-based application that produces publication-quality geogra

David Shorthouse 28 Mar 17, 2022
A plugin for Blessing Skin Server that can let you display Google Ads with Google AdSense in the website.

A plugin for Blessing Skin Server that can let you display Google Ads with Google AdSense in the website.

Big_Cake 2 Jan 25, 2022
Laravel-veneer - A suite of mocked services to use in your Laravel tests.

Laravel Veneer A suite of fixture data and methods to help make mocking 3rd party services easier. Overview Laravel Veneer aims to solve two problems

Oh See Software 4 Jun 23, 2022
a Google API v3 wrapper for Laravel 4.x

A Google API v3 wrapper for Laravel 4 This package enables a Laravel flavoured way to manage Google services through its API interface (v3) Installati

null 4 Nov 29, 2022
Adds phone number functionality to Laravel based on the PHP port of Google's libphonenumber API by giggsey.

Laravel Phone Adds phone number functionality to Laravel based on the PHP port of Google's libphonenumber API by giggsey. Table of Contents Demo Insta

null 2.1k Jan 2, 2023
A Laravel (php) package to interface with the geo-location services at geonames.org.

geonames v7.x A Laravel (php) package to interface with the geo-location services at geonames.org. Major Version Jump I jumped several major versions

Michael Drennen 82 Nov 24, 2022
Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

Introduction Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services. It handles almost all of the boilerpl

The Laravel Framework 2.2k Jan 4, 2023
Laravel Cashier Paddle provides an expressive, fluent interface to Paddle's subscription billing services.

Introduction Laravel Cashier Paddle provides an expressive, fluent interface to Paddle's subscription billing services. It handles almost all of the b

The Laravel Framework 189 Jan 5, 2023
Zarinpal is a laravel package to easily use zarinpal.com payment services in your applications

پکیج اتصال به درگاه پرداخت زرین پال zarinpal.com برای اتصال به درگاه پرداخت اینترنتی زرین پال و استفاده از api های آن می توانید از این پکیج استفاده کن

Rahmat Waisi 4 Jan 26, 2022
Generate services in Laravel with the artisan command

Laravel Service Generator Quickly generate services for your projects! Table of Contents Features Installation Usage Generate services Generate servic

Tim Wassenburg 15 Dec 2, 2022
A package for integrating Lazerpay services with your laravel application

This is my package lazerpay-laravel This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. Support

Abdulsalam Ishaq 5 Dec 22, 2022
Generate services and contracts in Laravel with the artisan command

What does it do? This package adds a new php artisan make:service {name} {--N|noContract} command. It will create a service file and its contract (int

Ludovic Guénet 18 Dec 21, 2022
A set of useful Laravel collection macros

A set of useful Laravel collection macros This repository contains some useful collection macros. Spatie is a webdesign agency based in Antwerp, Belgi

Spatie 1.5k Dec 31, 2022
Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Egor Shitikov 87 Nov 26, 2022
A collection of generators for Lumen and Laravel 5.

Lumen generators A collection of generators for Lumen and Laravel 5. Contents Why ? Installation Quick Usage Detailed Usage Model Generator Migration

Amine Ben hammou 349 Mar 24, 2022
A collection of extensions for Laravel development in Visual Studio Code

Laravel Extension Pack for Visual Studio Code Includes the basic extensions to get started with Laravel development in Visual Studio Code. Laravel Ext

Winnie Lin 24 Dec 25, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022