alex-kalanis/google-maps-php-services 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

alex-kalanis/google-maps-php-services

Composer 安装命令:

composer require alex-kalanis/google-maps-php-services

包简介

PHP client library(SDK) for Google Maps API Web Services

README 文档

README

Google Maps Services for PHP


PHP client library(SDK) for Google Maps API Web Services.

Fork of older Nick Tsai's library.

Build Status Scrutinizer Code Quality Latest Stable Version Minimum PHP Version Downloads License Code Coverage

Differences:

  • Minimal php is 8.1
  • Type checks
  • Dependency injection
  • With PSR and other remote libraries than Guzzle/Curl in mind
  • Only API key now usable

OUTLINE

DEMONSTRATION

For nearly any raw php / custom frameworks:

// somewhere in configuration something like this

/// ... with anonymous function as setter in DI
function (): \kalanis\google_maps\ClientConfig
{
    return \kalanis\google_maps\ClientConfig::init('Your API Key');
}

Then on desired pages:

class YourPresenter extends YourFramework
{
    public function __construct(
        // ... other used classes
        protected readonly kalanis\google_maps\Client $mapService,
    ) {
    }

    public function process(): void
    {
        // Geocoding an address
        $geocodeResult = $this->mapService->geocode('Pelješki most, Croatia');

        // Look up an address with reverse geocoding
        $reverseGeocodeResult = $this->mapService->reverseGeocode(42.916667, 17.533333);

        // Request directions via public transit
        $directionsResult = $this->mapService->directions('Ploče', 'Dubrovnik', [
            'mode' => "transit",
            'departure_time' => time(),
        ]);
    }
}

For Laravel:

/// app\Providers\AppServiceProvider.php
public function register()
{
    // ... other binds
    $this->app->bind(\kalanis\google_maps\Client::class, function(
            \Psr\Http\Client\ClientInterface $client,
            \Psr\Http\Message\RequestInterface $request,
        ): \kalanis\google_maps\Client {
            return new \kalanis\google_maps\Client(
                $request,
                $client,
                \kalanis\google_maps\ClientConfig::init('Your API Key'),
            );
        }
    );
}

And then in the controller is the code the same as in another random framework.

For Symfony:

# config/services.yaml
services:
  kalanis\google_maps\ClientConfig:
    arguments: ['Your API Key']
  kalanis\google_maps\Client:
    arguments: ['@Psr\Http\Message\RequestInterface', '@Psr\Http\Client\ClientInterface', '@kalanis\google_maps\ClientConfig']
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/your-maps')]
class YourMapsPresenter extends AbstractController
{
    public function __construct(
        // ... other used classes
        protected readonly kalanis\google_maps\Client $mapService,
    ) {
    }

    #[Route('/geocode', name: 'maps_geocode', defaults: ['where' => 'Pelješki most, Croatia'], methods: ['GET'])]
    public function geocode(Request $request, string $where): Response
    {
        $geocodeResult = $this->mapService->geocode($where);
        return new JsonResponse($geocodeResult)
    }

    #[Route('/reverse-geocode', lat: '42.916667', lon: '17.533333', defaults: ['lat' => '42.916667', 'lon' => '17.533333'], methods: ['GET'])]
    public function reverseGeocode(Request $request, string $lat, string $lon): Response
    {
        $geocodeResult = $this->mapService->reverseGeocode([$lat, $lon]);
        return new JsonResponse($geocodeResult)
    }
}

For Nette:

services:
    # ... other ones
    - kalanis\google_maps\ClientConfig('Your API Key')
    - kalanis\google_maps\Client
    # ... other ones

Or with parameters for different servers/services:

parameters:
    # ... other ones
    googleMapsKey: 'Your API Key'
    # ... other ones

services:
    # ... other ones
    - kalanis\google_maps\ClientConfig(%parameters.googleMapsKey%)
    - kalanis\google_maps\Client
    # ... other ones

And then in class like in other frameworks with DI.

DESCRIPTION

The PHP Client for Google Maps Services is a PHP Client library for the following Google Maps APIs:

REQUIREMENTS

  • PHP 8.1+ or higher

API keys

Each Google Maps Web Service request requires an API key or client ID. API keys are freely available with a Google Account at https://developers.google.com/console. The type of API key you need is a Server key.

To get an API key:

  1. Visit https://developers.google.com/console and log in with a Google Account.

  2. Select one of your existing projects, or create a new project.

  3. Enable the Google Maps Services API(s) you plan to use, such as:

    • Directions API
    • Distance Matrix API
    • Geocoding API
    • Places API
    • Roads API
    • Time Zone API
    • Nearby API
  4. Create a new Server key.

  5. If you'd like to restrict requests to a specific IP address, do so now.

For guided help, follow the instructions for the Directions API. You only need one API key, but remember to enable all the APIs you need. For even more information, see the guide to API keys.

Important: This key should be kept secret on your server.

INSTALLATION

Run Composer in your project:

composer require alex-kalanis/google-maps-php-services

Then you could call it after Composer is loaded depended on your PHP framework:

require __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

use kalanis\google_maps\Client;

USAGE

Before using any Google Maps Services, first you need to create a Client with configuration, then use the client to access Google Maps Services.

Client

Create a Client using API key:

$gmaps = new \kalanis\google_maps\Client(
    new \PsrMock\Psr7\Request(),
    new \PsrMock\Psr18\Client(),
    new \kalanis\google_maps\ConfigClient('Your API Key'),
);

Language

You could set language for Client for all services:

$gmaps = new \kalanis\google_maps\Client(
    new \PsrMock\Psr7\Request(),
    new \PsrMock\Psr18\Client(),
    new \kalanis\google_maps\ConfigClient('Your API Key', 'pt-br'),
);

list of supported languages - Google Maps Platform

APIs

Elevation API

Elevation API overview | Google for Developers

// Get elevation by locations parameter
$elevationResult = $gmaps->elevation(25.0339639, 121.5644722);
$elevationResult = $gmaps->elevation('25.0339639', '121.5644722');

Routes API

Get a route | Google for Developers

$routes = $gmaps->computeRoutes($originArray, $destinationArray, $fullBodyArray, $fieldMask)

// Get the route data between two places simply
$routes = $gmaps->computeRoutes([
        "location" => [
           "latLng" => [
              "latitude" => 37.419734,
              "longitude" => -122.0827784
           ]
        ]
    ],
    [
        "location" => [
           "latLng" => [
              "latitude" => 37.41767,
              "longitude" => -122.079595
           ]
        ]
    ]);

// Get the full route data between two places with full request data
$routes = $gmaps->computeRoutes([...], [...], ["travelMode": "DRIVE", ...], '*');

Roads API

Snap to Roads | Google for Developers

$roads = $gmaps->snapToRoads([[-35.27801,149.12958], [-35.28032,149.12907], [-35.28099,149.12929]]);

Directions API

Getting directions | Google for Developers

// Request directions via public transit
$directionsResult = $gmaps->directions('Milano', 'Venezia', [
    'mode' => "transit",
    'departure_time' => time(),
]);

Distance Matrix API

Get started with the Distance Matrix API | Google for Developers

// Get the distance matrix data between two places
$distanceMatrixResult = $gmaps->distanceMatrix('Canberra', 'Perth');

// With Imperial units
$distanceMatrixResult = $gmaps->distanceMatrix('Stonehenge', 'Bristol', [
    'units' => 'imperial',
]);

Geocoding API

Geocoding API overview | Google for Developers

// Geocoding an address
$geocodeResult = $gmaps->geocode('Avenida Maracanã 350, Rio de Janeiro');

// Look up an address with reverse geocoding
$reverseGeocodeResult = $gmaps->reverseGeocode(-22.912167, -43.230164);

Geolocation API

Geolocation API overview | Google for Developers

// Simple geolocate
$geolocateResult = $gmaps->geolocate([]);

Time Zone API

Time Zone API overview | Google for Developers

// requests the time zone data for given location
$timezoneResult = $gmaps->timezone([25.381111, 83.021389]); // Sárnáth

Nearby API

Nearby API overview | Google for Developers

// requests the nearby points for given location
$nearbyResult = $gmaps->nearby('restaurant', [25.71874, 32.6574]); // in Luxor

Find by Place API

Find by Place API overview | Google for Developers

// requests the place points for given location by given place
$nearbyResult = $gmaps->findPlace('Champs Elysees', 'restaurant', ['name', 'current_opening_hours']);

Find by Text API

Find by Text API overview | Google for Developers

// requests the place points for given location by given text
$nearbyResult = $gmaps->findText('Sagrada Familia', 350, [], 3, 0, true);

Place details API

Place details API overview | Google for Developers

// requests the details about place point
$nearbyResult = $gmaps->placeDetails('ChIJN1t_tDeuEmsRUsoyG83frY4', ['name', 'current_opening_hours']);

alex-kalanis/google-maps-php-services 适用场景与选型建议

alex-kalanis/google-maps-php-services 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 13 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 08 月 04 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「sdk」 「google maps」 「services」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 alex-kalanis/google-maps-php-services 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 alex-kalanis/google-maps-php-services 我们能提供哪些服务?
定制开发 / 二次开发

基于 alex-kalanis/google-maps-php-services 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 13
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 12
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-08-04