metasyntactical / google-directions-client
用于向由给定坐标组成的路线添加插值点的 Google Directions API 客户端。
Requires
- php: ^7.1
- beberlei/assert: ^2.9
- guzzlehttp/guzzle: ^6.3
- metasyntactical/http-transport-guzzle: ^1.1
- psr/log: ^1.0
Requires (Dev)
- codeclimate/php-test-reporter: ^0.4
- gamez/psr-testlogger: ^2.0
- phpunit/phpunit: ^7
README
什么是 MetaSyntactical/GoogleDirections?
MetaSyntactical/GoogleDirections 是一个用于 Google Maps Directions API 的 PHP 客户端库。其目的是计算给定地理坐标之间的路线。
使用 Google Directions API 的先决条件
要使用此库,您需要一个可以从 Google 获得的 Google API 密钥。使用 Google API 受 Google 设定的条款和条件的约束。根据您想要使用 Google API 的方式以及流量/请求数量,Google 可能会收取费用。有关详细信息,请参阅 Google Maps Directions API。
安装
安装此库的最简单方法是将其作为依赖项添加到项目的 composer.json 文件中。
$ composer require metasyntactical/google-directions-client "^2"
如果您使用的是 PHP 版本 5.5.x、5.6.x 或 7.0.x,您可以将库回退到早期兼容版本
$ composer require metasyntactical/google-directions-client "^1"
用法
要使用此库,请创建客户端类的实例
use MetaSyntactical\GoogleDirections\Client as GoogleApiClient;
use MetaSyntactical\GoogleDirections\Polyline as Polyline;
use MetaSyntactical\GoogleDirections\RouteFactory;
use GuzzleHttp\Client as HttpClient;
use MetaSyntactical\Http\Transport\Guzzle\GuzzleTransport;
$guzzleTransport = new GuzzleTransport(new HttpClient());
$polylineDecoder = new Polyline();
$googleApiClient = new GoogleApiClient(
'string', // <= your Google API key
$polylineDecoder,
$guzzleTransport
);
客户端类有一些依赖关系,必须在构造函数中传递
- 包含 HTTP 客户端并用于 Google API 客户端处理 HTTP 通信的 GuzzleTransport 对象
- 包含解码 Google Polylines 方法的 Polyline 对象(归功于 Peter Chng)
您可以选择在 Google API 客户端对象和 Polyline 对象上设置一个记录器以收集消息。您传递的记录器对象必须实现 PSR-3 记录器接口。
$googleApiClient->setLogger($logger);
$polylineDecoder->setLogger($logger);
客户端使用 Route 对象作为值对象来处理地理坐标。获取路线对象的最简单方法是通过工厂,该工厂将接受一个逗号分隔的坐标数组(lat,long),您想要计算路线
$coordinates = array(
'50.1109756,8.6824697',
'50.1131057,8.6935646',
'50.1114651,8.704576',
'50.1128467,8.7049644'
);
$routeFactory = new RouteFactory();
$route = $routeFactory->createRoute($coordinates);
请注意,坐标的顺序很重要,这意味着路线将从第一个给定的坐标开始,并按给定顺序通过任何其他坐标,直到最后一个给定的坐标。
与 Polyline 对象一样,您可以将 PSR-3 记录器传递给路线工厂以收集消息
$routeFactory->setLogger($logger);
要获取插值路线,请调用 Google API 客户端的 getDirections() 方法并传递路线对象作为参数
$resultRoute = $googleApiClient->getDirections($route);
返回值将是一个 Route 对象。根据路线的大小(坐标数量),一次 API 调用(即 getDirections() 方法的调用)将只产生部分结果。这是由于 Google API 每个请求只能处理有限数量的航点。
您可以通过调用 getRemainingCoordinateCount() 方法来检查路线中是否还有坐标需要通过调用 Google API 进行额外调用。
$resultRoute->getRemainingCoordinateCount();
如果计数大于零,只需再次以结果路线作为参数调用 getDirections() 方法,Google API 会被再次调用,产生路线的另一部分。
$resultRoute = $googleApiClient->getDirections($route);
一旦没有更多剩余坐标,可以通过在结果路线对象上调用 getInterpolatedRoute() 方法来检索组成插值路线的所有坐标。
$resultRoute->getInterpolatedRoute();
请注意,getInterpolatedRoute()方法返回一个坐标对象数组,这些坐标对象有获取纬度和经度值的方法
$coordinate->getLatitude();
$coordinate->getLongitude();