clevyr / laravel-geocoder

处理将地址转换为经纬度的地理编码,支持多个服务提供商

v0.1.1 2022-08-22 21:27 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

基于云服务提供商将地址转换为经纬度的地理编码。

注意: 目前仅支持使用 Google 作为地理编码提供商。我们将优先实现 MapBox。

安装

您可以通过 composer 安装此包

composer require clevyr/laravel-geocoder

接下来,发布插件资源

php artisan vendor:publish --provider="Clevyr\LaravelGeocoder\LaravelGeocoderServiceProvider"

这是发布的配置文件的内容(不含描述性注释)

return [
    'adapter' => 'google',
    'test-adapter' => 'test',
    'test' => [
        'lat' => 35.4771302,
        'lng' => -97.5283204,
    ],
];

设置 Google 地理编码

首先,您需要 设置 Google 地理编码 API 密钥

然后,您需要在您的 Laravel 应用程序中设置以下 ENV 变量

GOOGLE_CLOUD_API_KEY=

使用方法

use Clevyr\LaravelGeocoder\LaravelGeocoder;

$coords = LaravelGeocoder::GetLatLngFromAddress(
    '123 Test Ln',
    null,
    'New York',
    'NY',
    '10001',
);

echo $coords;

// [
//     "lat" => 40.7607184,
//     "lng" => -73.9613766,
// ]

或者,您可以在您的 Laravel Eloquent 模型中包含 Geocodable 特性以获取一些有用的地理编码实例方法

use Clevyr\LaravelGeocoder\Traits\Geocodable;

class MyModel extends Model
{
    use Geocodable;
}

$model = MyModel::find(1);
$coords = $model->getLatAndLong();

$model->name = 'New Name';
$model->addressIsDirty(); // false

$model->address_line_1 = '123 Foo Ln.';
$model->addressIsDirty(); // true

修改模型地理定位字段

默认情况下,当您使用 Geocodable 特性时,Laravel Geocoder 会默认使用以下字段在您的模型上

  • address_line_1(必需)
  • address_line_2
  • city(必需)
  • state(必需)
  • postal_code(必需)
  • country(默认为 'US')

但是,您可以使用以下模型中的 getter 函数按模型修改这些字段

    // Override the postal_code property with something specific to this model
    public function getGeocoderPostalCodeAttribute()
    {
        return 'zip';
    }

这假设该模型中有一个 zip 字段,然后它将被用于该模型的地理定位。以下是您可以覆盖的完整 getter 函数列表

public function getGeocoderAddressLine1Attribute();
public function getGeocoderAddressLine2Attribute();
public function getGeocoderCityAttribute();
public function getGeocoderStateAttribute();
public function getGeocoderPostalCodeAttribute();
public function getGeocoderCountryAttribute();

测试

composer test

代码检查

composer analyse

Laravel Pint

Laravel Pint 是一个针对简约主义者的 PHP 代码风格修复器。

./vendor/bin/pint

变更日志

有关最近更改的更多信息,请参阅 变更日志

安全漏洞

请审查我们关于如何报告安全漏洞的 安全策略

致谢

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件