### Composer Installation Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Command to install the Google Maps library using Composer. ```bash composer require alexpechkarev/google-maps ``` -------------------------------- ### Example: Fetching Routes with Parameters and Field Mask Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/routes.md Demonstrates how to set route parameters and a field mask before fetching route data. The example shows how to access distance, duration, and decoded polylines from the response. ```php $routeParams = [ '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, ]; $response = \GoogleMaps::load('routes') ->setParam($routeParams) ->setFieldMask('routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline') ->fetch(); // Response is already a PHP array: if (!empty($response['routes'])) { foreach ($response['routes'] as $route) { echo $route['distanceMeters']; echo $route['duration']; // If decodePolyline is enabled: $points = $route['polyline']['decodedPolyline']; foreach ($points as $point) { echo "Lat: {$point[0]}, Lng: {$point[1]}\n"; } } } ``` -------------------------------- ### Routes API Usage Example Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/configuration.md Example of how to load and use the Routes API service with specified parameters. ```php \GoogleMaps::load('routes')->setParam([...])->fetch(); ``` -------------------------------- ### Basic Geocoding Usage Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md A simple example of using the library for geocoding, setting an address parameter, and getting the response. ```php // Geocoding $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); ``` -------------------------------- ### Production Configuration Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/configuration.md A production-ready setup with SSL verification enabled, longer timeouts, and request compression. ```php 'key' => env('GOOGLE_MAPS_KEY'), 'ssl_verify_peer' => true, // Enable SSL verification 'connection_timeout' => 10, // Longer timeout 'request_timeout' => 60, 'request_use_compression' => true // Enable compression ``` -------------------------------- ### Geocoding API Usage Example Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Demonstrates how to use the Geocoding API to get location data. Load the 'geocoding' service, set parameters, and call `get()` to execute the request. Remember to decode the JSON response. ```php $response = \GoogleMaps::load('geocoding') ->setParam (['address' =>'santa cruz']) ->get(); ``` -------------------------------- ### Getting JSON Response Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Example of loading the geocoding service, setting a parameter, and retrieving a JSON string response. ```php $response = \GoogleMaps::load('geocoding')->get(); $data = json_decode($response, true); ``` -------------------------------- ### Load Directions Service Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/directions.md Automatically created via GoogleMaps::load('directions'). No setup code is shown. ```php public function __construct() ``` -------------------------------- ### Example RouteModifiers Object Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/types.md An example of RouteModifiers to configure route preferences. ```php 'routeModifiers' => [ 'avoidTolls' => false, 'avoidHighways' => false, 'avoidFerries' => false ] ``` -------------------------------- ### Loading and Configuring Services Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Demonstrates how to load different services and configure them using parameters and endpoints. Use `load` to get a service instance, `setParam` or `setParamByKey` to add parameters, and `setEndpoint` to specify the target API endpoint. ```php \GoogleMaps::load(string $service): WebService|Routes \GoogleMaps::load('service')->setParam(array): $this \GoogleMaps::load('service')->setParamByKey(string, mixed): $this \GoogleMaps::load('service')->setEndpoint(string): $this \GoogleMaps::load('service')->setFieldMask(string): $this // Routes API only ``` -------------------------------- ### Testing with Facades Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/facade.md Example of how to mock the GoogleMapsFacade in unit tests using shouldReceive for method mocking. ```php use Illuminate\Support\Facades\Facade; use GoogleMaps\Facade\GoogleMapsFacade; class GeocodingTest extends TestCase { public function test_geocoding_lookup() { GoogleMapsFacade::shouldReceive('load') ->with('geocoding') ->andReturnSelf() ->shouldReceive('setParamByKey') ->with('address', 'Santa Cruz') ->andReturnSelf() ->shouldReceive('get') ->andReturn('{"status":"OK","results":[]}'); $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); $this->assertStringContainsString('OK', $response); } } ``` -------------------------------- ### Coordinate Array (GET APIs) Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/types.md Illustrates how to format coordinate arrays for GET APIs, either as a pipe-separated string or a PHP array. ```php 'locations' => '39.7391536,-104.9847034|40.7128,-74.0060' ``` ```php 'locations' => ['39.7391536,-104.9847034', '40.7128,-74.0060'] ``` -------------------------------- ### Handling 'Unable to find config file' Error Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/errors.md Example of catching the specific ErrorException when the googlemaps configuration file is not found. ```php try { \GoogleMaps::load('geocoding'); } catch (ErrorException $e) { // "Unable to find config file." } ``` -------------------------------- ### Example LatLng Object Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/types.md An example of a LatLng object representing a specific geographic coordinate. ```php [ 'latitude' => 37.419734, 'longitude' => -122.0827784 ] ``` -------------------------------- ### Example BoundingBox Object Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/types.md An example of a BoundingBox object for biasing geographic search results. ```php 'bounds' => [ 'southwest' => ['latitude' => 34.0522, 'longitude' => -118.2437], 'northeast' => ['latitude' => 37.7749, 'longitude' => -122.4194] ] ``` -------------------------------- ### Testing with Facades Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/facade.md Example of how to mock the GoogleMapsFacade in unit tests using `shouldReceive`. ```APIDOC ## Example: Testing with Facades ### Description Unit tests can mock the facade to isolate the code under test. ### Method N/A (Facade pattern) ### Endpoint N/A (Facade pattern) ### Parameters N/A (Facade pattern) ### Request Example ```php use Illuminate\Support\Facades\Facade; use GoogleMaps\Facade\GoogleMapsFacade; class GeocodingTest extends TestCase { public function test_geocoding_lookup() { GoogleMapsFacade::shouldReceive('load') ->with('geocoding') ->andReturnSelf() ->shouldReceive('setParamByKey') ->with('address', 'Santa Cruz') ->andReturnSelf() ->shouldReceive('get') ->andReturn('{"status":"OK","results":[]}'); $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); $this->assertStringContainsString('OK', $response); } } ``` ### Response N/A (Facade pattern - response is from the mocked service) ``` -------------------------------- ### Access Google Maps Service Instance Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/service-provider.md Access the registered Google Maps service instance using the application container. This example shows how to get the instance and use its methods. ```php $instance = app('GoogleMaps'); $instance->load('geocoding')->setParamByKey('address', 'Santa Cruz')->get(); ``` -------------------------------- ### Migrating from Directions API to Routes API Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/integration-guide.md This example shows the transition from the older Directions API to the newer Routes API for calculating routes. Note the different parameter structure and method names. ```php // old: directions api $response = \googlemaps::load('directions') ->setparam([ 'origin' => '37.419734,-122.0827784', 'destination' => '37.417670,-122.079595', 'mode' => 'driving', ]) ->get(); // new: routes api $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', ]) ->fetch(); ``` -------------------------------- ### Example Location Object (Routes API) Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/types.md An example of a Location object for the Routes API. ```php [ 'location' => [ 'latLng' => [ 'latitude' => 37.419734, 'longitude' => -122.0827784 ] ] ] ``` -------------------------------- ### Configuring Response Format Endpoints Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/errors.md Example configuration for the 'endpoint' array, specifying JSON and XML response formats. ```php 'endpoint' => [ 'json' => 'json?', 'xml' => 'xml?', ], ``` -------------------------------- ### Basic Geocoding Configuration Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/configuration.md A basic setup for geocoding, including API key, SSL verification, and timeouts. ```php 'key' => env('GOOGLE_MAPS_KEY'), 'ssl_verify_peer' => false, 'connection_timeout' => 5, 'request_timeout' => 30, 'endpoint' => [ 'json' => 'json?', 'xml' => 'xml?', ], ``` -------------------------------- ### Handling 'Unknown Service' Error Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/errors.md Example of catching the specific ErrorException when an invalid service name is requested. ```php try { \GoogleMaps::load('invalid_service'); } catch (ErrorException $e) { // "Web service must be declared in the configuration file." } ``` -------------------------------- ### Install Google Maps Package Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Use Composer to add the google-maps package to your Laravel project. ```php composer require alexpechkarev/google-maps ``` -------------------------------- ### Google Maps API Usage Pattern Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/googlemaps.md Demonstrates the standard fluent interface pattern for interacting with Google Maps services: load the service, configure parameters, and execute the request. Use `get()` for most services and `fetch()` specifically for the Routes API. ```php // Pattern: Load → Configure → Execute \GoogleMaps::load('service-name') ->setParam([...]) // or ->setParamByKey('key', 'value') ->get() // or ->fetch() for Routes API ``` -------------------------------- ### Elevation API Request Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/endpoints.md Retrieve elevation data for given locations or a path. This example shows setting a single location. ```php \GoogleMaps::load('elevation') ->setParamByKey('locations', '39.7391536,-104.9847034') ->get(); ``` -------------------------------- ### get() Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/webservice-core.md Executes the HTTP request and returns the API response. Can return the raw response string or extract specific data using dot notation. Note: Not available for Routes API services; use `fetch()` instead. ```APIDOC ## get() ### Description Executes the HTTP request and returns the response. For APIs using GET requests, returns raw response string (JSON or XML). For extracting specific response keys, pass the key parameter. ### Method ```php public function get(string|false $needle = false): string|array ``` ### Parameters #### Query Parameters - **needle** (string|false) - Optional - Use dot notation to extract specific response keys (e.g., 'results.formatted_address'). Defaults to `false`. ### Returns - **string|array** - Response string or array of extracted values. ### Throws - **ErrorException** - On cURL errors or invalid responses. ### Important Not available for Routes API (`routes`, `routematrix` services). Use `fetch()` instead. ### Example ```php // Get full response $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'santa cruz') ->get(); $decoded = json_decode($response, true); // Extract specific key from response $addresses = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'santa cruz') ->get('results.formatted_address'); ``` ``` -------------------------------- ### Places API (New) Text Search Example Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/endpoints.md Fetches places based on a text query, specifying language and maximum results. Requires setting a field mask for desired place data. ```php \GoogleMaps::load('places_textsearch') ->setParam([ 'textQuery' => 'restaurants in New York', 'languageCode' => 'en', 'maxResultCount' => 10 ]) ->setFieldMask('places.id,places.displayName,places.formattedAddress,places.types') ->fetch(); ``` -------------------------------- ### Executing API Requests and Retrieving Responses Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Shows how to execute API requests and retrieve responses. Use `get` for most APIs, `getResponseByKey` for specific response data, and `getStatus` for the API status. The Routes API offers additional methods like `fetch`, `setFieldMask`, `decodePolyline`, `isLocationOnEdge`, and `containsLocation`. ```php // Most APIs \GoogleMaps::load('service')->get(): string \GoogleMaps::load('service')->get(string $key): array \GoogleMaps::load('service')->getResponseByKey(string): array \GoogleMaps::load('service')->getStatus(): mixed // Routes API only \GoogleMaps::load('routes')->fetch(): array \GoogleMaps::load('routes')->setFieldMask(string): $this \GoogleMaps::load('routes')->decodePolyline(string): array \GoogleMaps::load('routes')->isLocationOnEdge(float, float, float): bool \GoogleMaps::load('routes')->containsLocation(float, float): bool ``` -------------------------------- ### Implement Rate Limiting for Geocoding Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/integration-guide.md Implement rate limiting to stay within API quotas, preventing excessive requests per user. This example limits to 50 requests per minute per user. ```php use Illuminate\Support\Facades\RateLimiter; class LocationService { public function geocodeAddress($address, $userId) { $key = 'geocode:' . $userId; // Limit to 50 requests per minute per user if (RateLimiter::tooManyAttempts($key, 50)) { throw new \Exception('Rate limit exceeded'); } RateLimiter::hit($key, 60); return \GoogleMaps::load('geocoding') ->setParamByKey('address', $address) ->get(); } } ``` -------------------------------- ### Get All Request Parameters Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/webservice-core.md Retrieves all currently set request parameters as an associative array. Useful for inspecting the complete set of parameters before making a request. ```php $params = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'santa cruz') ->getParam(); // Returns: ['address' => 'santa cruz', ...] ``` -------------------------------- ### get( $key ) Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Executes the request for all APIs except the Routes API. Optionally accepts a 'dot' notation key to retrieve a specific part of the response. Returns a JSON string or XML string if configured. ```APIDOC ## get( $key ) ### Description Executes the request. This method is not available for the Routes API. If a key is provided, it attempts to return only that part of the response. ### Method get ### Parameters #### Path Parameters - **key** (string) - Optional - A 'dot' notation key to retrieve a specific part of the response. ### Request Example ```php $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'santa cruz') ->setParamByKey('components.administrative_area', 'TX') ->get(); var_dump( json_decode( $response ) ); ``` ### Response Returns a JSON string (or XML string if configured). ### Response Example ```json { "results" : [ { "address_components" : [ { "long_name" : "277", "short_name" : "277", "types" : [ "street_number" ] }, ... } ``` ### Example with $key parameter ```php $response = \GoogleMaps::load('geocoding') ->setParamByKey('latlng', '40.714224,-73.961452') ->get('results.formatted_address'); var_dump( json_decode( $response ) ); ``` ### Response Example with $key parameter ```php 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" ] ... ] ``` ``` -------------------------------- ### Get Routes with Specific Fields Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Fetch route information including duration and distance for a given origin and destination. This uses the POST method and returns a PHP array directly. ```php $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', ]) ->setFieldMask('routes.duration,routes.distanceMeters') ->fetch(); ``` -------------------------------- ### Configuring API Key in PHP Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/errors.md Shows how to set the API key in the config file or via an environment variable. ```php 'key' => 'YOUR_GOOGLE_MAPS_API_KEY', ``` ```php 'key' => env('GOOGLE_MAPS_KEY'), ``` -------------------------------- ### Facade vs. Service Container Usage Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/facade.md Demonstrates equivalent ways to access the Google Maps service, either through the facade or directly via the service container. ```php // Using Facade (static-like) $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); // Using service container directly $response = app('GoogleMaps') ->load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); // Dependency injection in controller class GeocodingController extends Controller { public function lookup(\GoogleMaps\GoogleMaps $maps) { $response = $maps ->load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); } } ``` -------------------------------- ### Setting Parameters Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Illustrates setting parameters individually using `setParamByKey` or multiple parameters at once using `setParam`. ```php // Individual parameters ->setParamByKey('address', 'Santa Cruz') ->setParamByKey('components.country', 'US') // Multiple parameters at once ->setParam(['address' => 'Santa Cruz', 'language' => 'en']) ``` -------------------------------- ### Fluent Interface for Configuration Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Demonstrates method chaining using the fluent interface where configuration methods return `$this`. ```php \GoogleMaps::load('service') ->setParamByKey('key', 'value') ->setEndpoint('json') ->get(); ``` -------------------------------- ### Loading Services Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Shows how to load different services like 'geocoding' or 'routes' using the `load()` method. ```php $service = \GoogleMaps::load('geocoding'); $service = \GoogleMaps::load('routes'); ``` -------------------------------- ### Initialize GoogleMaps Service Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Instantiate the main GoogleMaps class to access various services. Alternatively, use the facade for static-like access. ```php use GoogleMaps\GoogleMaps; $maps = new GoogleMaps(); $service = $maps->load('service-name'); ``` ```php \GoogleMaps::load('service-name'); ``` -------------------------------- ### Fluent Interface for Geocoding Configuration Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Demonstrates chaining configuration methods for the Geocoding service. Use this pattern to set parameters and retrieve data efficiently. ```php \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->setParamByKey('components.country', 'US') ->setEndpoint('json') ->get(); ``` -------------------------------- ### Publish Configuration File Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Run the Artisan command to publish the googlemaps configuration file to your project. ```php php artisan vendor:publish --tag=googlemaps ``` -------------------------------- ### GoogleMaps Entry Point Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md The GoogleMaps class is the main entry point for accessing all API services. You can instantiate it directly or use the provided Facade for static-like access. ```APIDOC ## GoogleMaps **Entry point for all API services.** ### Usage ```php use GoogleMaps\GoogleMaps; $maps = new GoogleMaps(); $service = $maps->load('service-name'); ``` Or via Facade: ```php \GoogleMaps::load('service-name'); ``` ### Methods - `load(string $service): WebService|Routes|Directions` **Namespace:** `GoogleMaps` ``` -------------------------------- ### Controller Integration using Facade Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/integration-guide.md Utilize the Google Maps facade for direct access to its methods without explicit dependency injection. This is a simpler approach for quick integration. ```php namespace App\Http\Controllers; class LocationController extends Controller { public function search(Request $request) { $address = $request->input('address'); $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', $address) ->get(); return response()->json(json_decode($response, true)); } } ``` -------------------------------- ### Facade Usage for Geocoding Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Demonstrates using the GoogleMaps facade to chain method calls for a geocoding request, including setting parameters and executing the request. ```php \GoogleMaps::load('geocoding')->setParamByKey('address', 'Santa Cruz')->get(); ``` -------------------------------- ### Get Elevation by Location Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Retrieve the elevation for a specific geographic location. The location is provided as a latitude and longitude string. ```php $response = \GoogleMaps::load('elevation') ->setParamByKey('locations', '39.7391536,-104.9847034') ->get(); ``` -------------------------------- ### Enable Request Compression Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/configuration.md Enable gzip compression for requests by setting the `Accept-Encoding` header. Defaults to `false`. ```php 'request_use_compression' => false ``` -------------------------------- ### Get Endpoint Format Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Retrieves the currently configured endpoint format (json or xml). Useful for verifying the current setting. ```php $endpoint = \GoogleMaps::load('geocoding') ->setEndpoint('json') ->getEndpoint(); echo $endpoint; // output 'json' ``` -------------------------------- ### Geocoding API - Get Address Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Performs geocoding to convert addresses to geographic coordinates. Parameters can be set using `setParam` or `setParamByKey`. ```APIDOC ## Geocoding API - Get Address ### Description Converts addresses into geographic coordinates. This method allows setting parameters using either a single array or individual key-value pairs. ### Method `get()` ### Parameters - `setParam` (array) - An associative array of parameters for the geocoding request, such as `address` and `components`. - `setParamByKey` (string, string) - Sets a parameter by key. For nested arrays, use dot notation (e.g., 'components.administrative_area'). ### Request Example (using `setParam`) ```php $response = \GoogleMaps::load('geocoding') ->setParam ([ 'address' =>'santa cruz', 'components' => [ 'administrative_area' => 'TX', 'country' => 'US', ] ]) ->get(); ``` ### Request Example (using `setParamByKey`) ```php $endpoint = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'santa cruz') ->setParamByKey('components.administrative_area', 'TX') //return $this ... ``` ### Response - `response` (mixed) - The result of the geocoding request. The exact structure depends on the API response. ``` -------------------------------- ### Configure API Key via Environment Variable Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/configuration.md Set your API key in a .env file and reference it in the configuration. ```env GOOGLE_MAPS_KEY=your_api_key_here ``` ```php 'key' => env('GOOGLE_MAPS_KEY'), ``` -------------------------------- ### Get Time Zone by Location and Timestamp Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Determine the time zone for a given location and a specific Unix timestamp. The response is automatically decoded into a PHP array. ```php $response = \GoogleMaps::load('timezone') ->setParam([ 'location' => '39.6034810,-119.6822510', 'timestamp' => '1331161200' ]) ->get(); ``` -------------------------------- ### Geolocation API Request Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/endpoints.md Get geolocation information based on cell towers and WiFi access points. This POST request requires an API key in the URL. ```php \GoogleMaps::load('geolocate') ->setParam([ 'homeMobileCountryCode' => 310, 'radioType' => 'gsm', 'cellTowers' => ['cellId' => 39627456], 'wifiAccessPoints' => ['macAddress' => '01:23:45:67:89:AB'] ]) ->get(); ``` -------------------------------- ### Get Single Request Parameter Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/webservice-core.md Retrieves the value of a specific request parameter using dot notation for nested keys. Returns null if the parameter is not set. ```php $address = \GoogleMaps::load('geocoding')->getParamByKey('address'); ``` -------------------------------- ### Get Current Response Endpoint Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/webservice-core.md Retrieves the currently configured response format (JSON or XML) for the WebService instance. Useful for verifying the active endpoint setting. ```php $format = \GoogleMaps::load('geocoding')->getEndpoint(); echo $format; // Outputs: 'json' ``` -------------------------------- ### Cache Geocoding API Responses Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/integration-guide.md Cache geocoding API responses to reduce quota usage and improve performance. This example uses Laravel's Cache facade. ```php use Illuminate\Support\Facades\Cache; class LocationService { public function geocodeAddress($address) { $cacheKey = 'geocode:' . md5($address); if (Cache::has($cacheKey)) { return Cache::get($cacheKey); } $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', $address) ->get(); $data = json_decode($response, true); if ($data['status'] === 'OK') { // Cache for 1 day Cache::put($cacheKey, $data['results'][0], now()->addDay()); } return $data['results'][0] ?? null; } } ``` -------------------------------- ### GoogleMaps::load() Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/googlemaps.md Bootstraps and returns a configured web service instance for various Google Maps services. This method allows you to load specific services like geocoding, routes, directions, and more, enabling chaining of further API calls. ```APIDOC ## GoogleMaps::load() ### Description Bootstraps and returns a configured web service instance. Routes to specialized implementations (e.g., Routes class for routes/routematrix) or base WebService for other APIs. ### Method Signature `public function load(string $service): WebService` ### Parameters #### Path Parameters - **$service** (string) - Required - Service name as defined in config: 'geocoding', 'routes', 'routematrix', 'directions', 'elevation', 'geolocate', 'snapToRoads', 'speedLimits', 'timezone', 'nearbysearch', 'textsearch', 'radarsearch', 'placedetails', 'placeadd', 'placedelete', 'placephoto', 'placeautocomplete', 'placequeryautocomplete', 'places_textsearch', 'places_nearby', 'places_details', 'places_photo' ### Returns `WebService|Routes|Directions` - Configured service instance (chaining enabled) ### Throws `ErrorException` - If configuration is invalid or missing ### Example ```php // Load Geocoding service $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); // Load Routes API service (new) $response = \GoogleMaps::load('routes') ->setParam($routeParams) ->fetch(); // Load Directions API service (deprecated) $response = \GoogleMaps::load('directions') ->setParam($directionParams) ->get(); ``` ``` -------------------------------- ### Get API Response Status Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/webservice-core.md Retrieve the status of the last API request using getStatus. This is crucial for handling different outcomes like 'OK', 'ZERO_RESULTS', or errors. ```php public function getStatus(): mixed ``` ```php $status = ->getStatus(); if ($status === 'ZERO_RESULTS') { echo 'No results found'; } ``` -------------------------------- ### Check API Response Status Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/errors.md After making an API call, check the response status to determine if the request was successful or if an error occurred. This example covers common status codes. ```php $response = GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); $status = GoogleMaps::load('geocoding')->getStatus(); switch ($status) { case 'OK': // Process results break; case 'ZERO_RESULTS': echo 'No results found'; break; case 'OVER_QUERY_LIMIT': echo 'Query limit exceeded'; break; case 'REQUEST_DENIED': echo 'Request denied - check API key'; break; case 'INVALID_REQUEST': echo 'Invalid request parameters'; break; } ``` -------------------------------- ### Google Maps Method Chaining for Configuration Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/googlemaps.md Illustrates how all configuration methods return `$this`, enabling a fluent and chainable interface for setting parameters and endpoints before executing the request. This allows for concise and readable API calls. ```php $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->setParamByKey('components.country', 'US') ->setEndpoint('json') ->get(); ``` -------------------------------- ### Multiple Service API Keys Configuration Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/configuration.md Configure different API keys for multiple services like Routes and Places. ```php 'key' => env('GOOGLE_MAPS_KEY'), 'service' => [ 'routes' => [ 'key' => env('ROUTES_API_KEY'), // Premium Routes API key // ... ], 'places_nearby' => [ 'key' => env('PLACES_API_KEY'), // Places API key // ... ], ] ``` -------------------------------- ### Handling Google Maps API Responses Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Demonstrates how to retrieve and process responses from Google Maps API calls, including getting raw string responses or decoded arrays. ```php $response = \GoogleMaps::load('geocoding')->setParamByKey('address', 'Santa Cruz')->get(); ``` ```php $response = \GoogleMaps::load('geocoding')->setParamByKey('address', 'Santa Cruz')->get($key); ``` ```php $response = \GoogleMaps::load('geocoding')->getResponseByKey('address', 'Santa Cruz'); ``` ```php $response = \GoogleMaps::load('geocoding')->setParamByKey('address', 'Santa Cruz')->fetch(); ``` -------------------------------- ### Publish All Package Assets Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/service-provider.md Use this command to publish all publishable assets from the Google Maps package, including configuration files and other resources. ```bash php artisan vendor:publish --provider="GoogleMaps\ServiceProvider\GoogleMapsServiceProvider" ``` -------------------------------- ### Available Methods via Facade Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/facade.md Lists the public methods available through the GoogleMapsFacade, which are delegated to the underlying GoogleMaps service. ```APIDOC ## Available Methods All public methods from `\GoogleMaps\GoogleMaps` are available through the facade. ### `load(string $service): WebService|Routes|Directions` Loads a specific Google Maps service (e.g., 'geocoding'). ### Inherited Methods from `WebService` (and specialized services): - `setEndpoint(string $key = 'json'): $this` - `getEndpoint(): string` - `setParamByKey(string $key, mixed $value): $this` - `getParamByKey(string $key): mixed` - `setParam(array $param): $this` - `getParam(): array` - `get(string|false $needle = false): string|array` - `getResponseByKey(string|false $needle = false): array` - `getStatus(): mixed` - `fetch(): array` (Routes class only) - `setFieldMask(string $fieldMask): $this` (Routes class only) - `isLocationOnEdge(float $lat, float $lng, float $tolerance = 0.1): bool` (Routes/Directions) - `containsLocation(float $lat, float $lng): bool` (Routes/Directions) ``` -------------------------------- ### Wrap API Calls in Try-Catch Block Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/errors.md Always wrap Google Maps API calls in a try-catch block to handle potential exceptions gracefully. This example demonstrates catching a generic ErrorException. ```php try { $response = GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); $data = json_decode($response, true); if (!empty($data['results'])) { // Process results } } catch (ErrorException $e) { Log::error('Google Maps API error: ' . $e->getMessage()); // Return error response to user } ``` -------------------------------- ### WebService Base Class Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md The WebService class serves as the base for all API services, handling HTTP communication and parameter management. It provides methods to set and get endpoints, parameters, and execute requests. ```APIDOC ## GoogleMaps\WebService **Base class for all services. Provides HTTP communication and parameter management.** ### Usage ```php $service = \GoogleMaps::load('geocoding'); // Returns WebService instance ``` ### Methods - `setEndpoint(string $key = 'json')` - `getEndpoint(): string` - `setParamByKey(string $key, mixed $value)` - `getParamByKey(string $key): mixed|null` - `setParam(array $param)` - `getParam(): array` - `get(string|false $needle = false): string|array` - `getResponseByKey(string|false $needle): array` - `getStatus(): mixed` **Namespace:** `GoogleMaps` ``` -------------------------------- ### Catching ErrorException in PHP Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/errors.md Demonstrates how to catch the generic ErrorException thrown by the package for any error condition. ```php try { $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); } catch (ErrorException $e) { echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Directions API - get() Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/directions.md Executes the HTTP request to the Directions API and returns the response. It supports decoding polylines automatically if configured. Use dot notation to extract specific response keys. ```APIDOC ## GET /directions ### Description Executes the HTTP request and returns the response with automatically decoded polylines if configured. Use dot notation to extract specific response keys. ### Method GET ### Endpoint /directions ### Parameters #### Query Parameters - **origin** (string) - Required - The starting point for the directions. - **destination** (string) - Required - The ending point for the directions. - **mode** (string) - Optional - The mode of transport (e.g., 'driving', 'walking', 'bicycling', 'transit'). ### Request Example ```php $response = \GoogleMaps::load('directions') ->setParam([ 'origin' => '37.419734,-122.0827784', 'destination' => '37.417670,-122.079595', 'mode' => 'driving', ]) ->get(); $data = json_decode($response, true); // If decodePolyline enabled, polyline is already decoded: foreach ($data['routes'][0]['overview_polyline']['points'] as $point) { echo "Lat: {$point[0]}, Lng: {$point[1]}\n"; } ``` ### Response #### Success Response (200) - **routes** (array) - An array of route objects, each containing details about a possible route. - **overview_polyline** (object) - Contains the encoded polyline string or decoded points. - **points** (array) - Array of coordinate pairs if polyline decoding is enabled. #### Response Example ```json { "routes": [ { "overview_polyline": { "points": [ [37.419734, -122.0827784], [37.417670, -122.079595] ] } } ] } ``` **Throws:** `ErrorException` - On request or decoding errors **Note:** If `decodePolyline` is enabled in config, `routes.overview_polyline.points` is automatically decoded from encoded polyline string to array of coordinate pairs. ``` -------------------------------- ### fetch() Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Executes the request specifically for the Routes API (routes and routematrix). Returns a decoded PHP array or throws an ErrorException. ```APIDOC ## fetch() ### Description Executes the request against the Routes API. This method is ONLY for the Routes API (`routes` and `routematrix`). ### Method fetch ### Response Returns a decoded PHP array directly or throws an `ErrorException`. ``` -------------------------------- ### Controller Integration with Dependency Injection Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/integration-guide.md Inject the GoogleMaps service into your controller's constructor for easy access. This method is recommended for better testability and adherence to SOLID principles. ```php namespace App\Http\Controllers; use GoogleMaps\GoogleMaps; class LocationController extends Controller { public function __construct(private GoogleMaps $maps) {} public function search(Request $request) { $address = $request->input('address'); $response = $this->maps->load('geocoding') ->setParamByKey('address', $address) ->get(); return response()->json(json_decode($response, true)); } } ``` -------------------------------- ### Check if Location is within Route Polygon Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/directions.md Determines if a given latitude and longitude point falls within the polygon defined by the directions response. This method requires that setParam() and get() have been called beforehand. No tolerance parameter is available. ```php $response = \GoogleMaps::load('directions') ->setParam([ 'origin' => '37.419734,-122.0827784', 'destination' => '37.417670,-122.079595', 'mode' => 'driving', ]) ->get(); if (\GoogleMaps::load('directions')->containsLocation(37.41764, -122.08293)) { echo 'Point is within the route polygon'; } ``` -------------------------------- ### Basic Facade Usage Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/facade.md Access the Google Maps service using the registered facade with static-like method calls. ```php // Static-like syntax \GoogleMaps::load('geocoding') ->setParamByKey('address', 'Santa Cruz') ->get(); ``` -------------------------------- ### Check if Location is on Route Edge Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/directions.md Determines if a given latitude and longitude point falls on or near the polyline of a previously fetched directions response. Requires that setParam() and get() have been called prior to execution. A tolerance in degrees can be specified. ```php $response = \GoogleMaps::load('directions') ->setParam([ 'origin' => '37.419734,-122.0827784', 'destination' => '37.417670,-122.079595', 'mode' => 'driving', ]) ->get(); if (\GoogleMaps::load('directions')->isLocationOnEdge(37.41665, -122.08175)) { echo 'Point is on or near the route'; } ``` -------------------------------- ### Format Parameters as Query String Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Use the Parameters utility class to format an array of parameters into a URL query string. Ensure parameters are passed by reference. ```php use GoogleMaps\Parameters; $queryString = Parameters::getQueryString($params); ``` -------------------------------- ### Execute HTTP Request and Get Response Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/webservice-core.md Executes the HTTP request to the Google Maps API and returns the response. Can return the raw response string or extract specific values using dot notation. Note: Not for Routes API; use fetch() instead. ```php // Get full response $response = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'santa cruz') ->get(); $decoded = json_decode($response, true); // Extract specific key from response $addresses = \GoogleMaps::load('geocoding') ->setParamByKey('address', 'santa cruz') ->get('results.formatted_address'); ``` -------------------------------- ### Error Handling with Try-Catch Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Demonstrates how to handle potential errors when making API requests using a try-catch block. ```php try { $response = \GoogleMaps::load('geocoding')->setParamByKey('address', 'Santa Cruz')->get(); } catch (ErrorException $e) { echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Load WebService Instance Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/API-SUMMARY.md Load a specific service, such as geocoding, which returns an instance of the WebService class for making API requests. ```php $service = \GoogleMaps::load('geocoding'); // Returns WebService instance ``` -------------------------------- ### Load Geocoding Service Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Loads the geocoding web service. This is the first step before setting parameters and making a request. ```php \GoogleMaps::load('geocoding') ... ``` -------------------------------- ### Service Configuration Structure Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/configuration.md Defines the general structure for configuring a service, including URL, type, key, endpoint behavior, and custom parameters. ```php 'service_name' => [ 'url' => 'https://...', 'type' => 'GET', // or 'POST' 'key' => null, // Uses master key if null 'endpoint' => true, // Whether to append endpoint suffix 'responseDefaultKey' => null, 'decodePolyline' => false, // For polyline-based APIs 'headers' => [...], // Custom HTTP headers 'param' => [...] // Accepted parameters ] ``` -------------------------------- ### Geocoding with setParam() Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Perform geocoding by setting parameters as an array of key-value pairs using `setParam()`. ```php $response = \GoogleMaps::load('geocoding') ->setParam ({ 'address' =>'santa cruz', 'components' => [ 'administrative_area' => 'TX', 'country' => 'US', ] }) ->get(); ``` -------------------------------- ### Set Connection Timeouts Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/configuration.md Configure the maximum time in seconds to establish a connection and wait for a response. Default connection timeout is 5 seconds, and request timeout is 30 seconds. ```php 'connection_timeout' => 5 ``` ```php 'request_timeout' => 30 ``` -------------------------------- ### Types Array (Places) Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/types.md Demonstrates the structure for a types array in Places requests. Note that the package only uses the first element due to Google's deprecation of multiple types. ```php 'types' => ['restaurant', 'cafe'] // Only first element used // Converted to: 'type' => 'restaurant' ``` -------------------------------- ### Fetching Routes API Response Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/INDEX.md Demonstrates fetching data from the Routes API, which directly returns a PHP array. ```php $data = \GoogleMaps::load('routes')->fetch(); // Already a PHP array ``` -------------------------------- ### Place Autocomplete (Legacy) Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/googlemaps.md Provides place predictions based on text input (legacy). ```APIDOC ## Place Autocomplete (Legacy) ### Description Provides place predictions based on text input (legacy). ### Method GET ### Endpoint maps.googleapis.com/maps/api/place/autocomplete/ ### Use Case Place autocomplete (legacy) ``` -------------------------------- ### load( $serviceName ) Source: https://github.com/alexpechkarev/google-maps/blob/master/README.md Loads the specified web service configuration by its name. This method returns a reference to the object itself, allowing for method chaining. ```APIDOC ## load( $serviceName ) ### Description Loads the specified web service configuration by its name. ### Method load ### Parameters #### Path Parameters - **serviceName** (string) - Required - The name of the web service to load (e.g., 'geocoding'). ### Request Example ```php \GoogleMaps::load('geocoding') ``` ### Response Returns reference to it's self ($this). ``` -------------------------------- ### Configure SSL Verification in Google Maps Package Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/integration-guide.md Set the 'ssl_verify_peer' option in config/googlemaps.php to control SSL verification. Use environment variables for dynamic configuration. ```php 'ssl_verify_peer' => env('GOOGLE_MAPS_VERIFY_SSL', true), ``` -------------------------------- ### Fetch Route and Check if Location is on Edge Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/routes.md First, fetch a route using setParam() and fetch(). Then, use isLocationOnEdge() to determine if a given latitude and longitude fall on or near the fetched route. Tolerance is specified in degrees. ```php $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', ]) ->fetch(); // Check if a point is on the route if (\GoogleMaps::load('routes')->isLocationOnEdge(37.41665, -122.08175)) { echo 'Point is on or near the route'; } ``` -------------------------------- ### Routes API (Recommended) Source: https://github.com/alexpechkarev/google-maps/blob/master/_autodocs/api-reference/googlemaps.md Calculates routes between locations. ```APIDOC ## Routes API (Recommended) ### Description Calculates routes between locations. ### Method POST ### Endpoint routes.googleapis.com/directions/v2:computeRoutes ### Use Case Route calculation (RECOMMENDED) ```