teampickr/php-google-maps-distance-matrix

Google Maps Distance Matrix API 的 PHP 实现

0.6 2020-10-03 14:50 UTC

This package is auto-updated.

Last update: 2024-08-29 04:48:30 UTC


README

这是一个简单的包,允许使用(主要是)流畅的 API 访问 Google Maps Distance Matrix API。该包支持 Google 提供的标准许可证和高级/企业许可证类型。

安装

使用 composer 安装此包

$ composer require teampickr/php-google-maps-distance-matrix

框架

目前我们仅对 Laravel 框架提供兼容性。但是,我们欢迎提供进一步框架特定行为的 PR,只要它不影响其他人的包使用,或者引入非可选依赖(建议)。

Laravel

如果你正在使用 Laravel,则可以使用我们的服务提供者。如果你使用的是 Laravel >5.5,则安装后包将被自动发现。否则,请将以下内容添加到你的 config/app.php 文件中

<?php

'providers' => [
    ...
    \TeamPickr\DistanceMatrix\Frameworks\Laravel\DistanceMatrixServiceProvider::class,
]

Facades

我个人不喜欢门面。然而,我知道有人喜欢它们。如果你使用的是 Laravel >5.5,则门面将被自动发现。否则,你可以在 config/app.php 文件中添加它。

<?php

'aliases' => [
    ...
    'DistanceMatrix' => \TeamPickr\DistanceMatrix\Frameworks\Laravel\DistanceMatrix::class,
]

配置

首先,请确保你已经复制了配置文件

$ php artisan vendor:publish --tag=config

这将创建一个 config/google.php 文件,这是你的 API 密钥/许可证信息被检索的地方。默认情况下,我们使用 .env 配置值来获取你的 API 密钥。

如果你有一个标准 API 密钥,你只需在 .env 中添加以下内容

GOOGLE_MAPS_KEY=MY-API-KEY

如果你是高级/企业 Google Maps 用户,并使用加密密钥和客户端 ID,则应在 .env 中添加以下内容

GOOGLE_LICENSE_TYPE=premium
GOOGLE_MAPS_CLIENT_ID=MY-CLIENT-ID
GOOGLE_MAPS_ENC_KEY=MY-ENCRYPTION-KEY

请确保不要将你的密钥存储在版本控制中!

使用方法

许可证/API 密钥

在发出请求之前,你需要创建你的许可证对象。如果你是标准 Google Maps 用户,那么你只需要 API 密钥,然后你可以按以下方式创建许可证

$license = new StandardLicense($apiKey);

如果你是高级/企业 Google Maps 用户,则需要按以下方式创建许可证

$license = new PremiumLicense($clientId, $encryptionKey);

然后,你可以开始发出请求

$request = new DistanceMatrix($license);

// or

$request = DistanceMatrix::license($license);

基本用法

$response = DistanceMatrix::license($license)
    ->addOrigin('norwich,gb')
    ->addDestination('52.603669, 1.223785')
    ->request();
   
// I want to make the following but of API better,
// as it looks horrible at the moment.
$rows = $response->rows();
$elements = $rows[0]->elements();
$element = $element[0];

$distance = $element->distance();
$distanceText = $element->distanceText();
$duration = $element->duration();
$durationText = $element->durationText();
$durationInTraffic = $element->durationInTraffic();
$durationInTrafficText = $element->durationInTrafficText();

// or

$response->json['destination_addresses'][0];
$response->json['rows'][0]['elements'][0]['distance']['value'];
$response->json['rows'][0]['elements'][0]['duration_in_traffic']['text'];