thorazine/location

基于 Google API 的 Laravel 地理位置反转器

3.1.1 2020-05-25 22:27 UTC

README

Total Downloads Latest Stable Version License

地理数据到地理位置

从坐标、地址、邮政编码或 IP 获取完整的标准化位置 PHP 数组或对象。通过位置外观,您可以请求 Google 和 IpInfo API 返回您网站上访客的地址。此脚本即用即装,无需任何密钥或注册。

需要注意的事项

此脚本使用 Google 地理数据和分析 API 来请求信息。特别是与 IP API 一起使用时,存在错误的空间。Google API 非常准确。然而,请不要将此数据作为事实,而应将其作为指示。

如何使其工作

运行

composer require thorazine/location

就是这样

如果您正在使用 Laravel < 5.5

您无法使用此版本。请访问 pre55 分支

其他可选内容

获取配置

php artisan vendor:publish --tag=location

如果您有 Google 密钥,请将其添加到 .env 文件中一行

GOOGLE_KEY=[key]

此脚本曾经无需密钥即可即用即装,但现在不再如此。感谢 Google。您可以在 这里 申请一个密钥。请确保它有足够的权限。

以下是一些(快速示例)

$location = Location::locale('nl')->coordinatesToAddress(['latitude' => 52.385288, 'longitude' => 4.885361])->get();

$location = Location::locale('nl')->addressToCoordinates(['country' => 'Nederland', 'street' => 'Nieuwe Teertuinen', 'street_number' => 25])->get();

$location = Location::locale('nl')->postalcodeToCoordinates(['postal_code' => '1013 LV', 'street_number' => '25'])->coordinatesToAddress()->get();

$location = Location::locale('nl')->postalcodeToCoordinates(['postal_code' => '1013 LV', 'street_number' => '25'], true)->get();

$location = Location::locale('nl')->ipToCoordinates('46.44.160.221')->coordinatesToAddress()->get(); // if IP resolves properly, which it mostly doesn't

$location = Location::locale('nl')->ipToCoordinates('46.44.160.221', true)->get(); // if IP resolves properly, which it mostly doesn't

都会得到以下结果

$location['latitude'] = 52.385288,
$location['longitude'] = 4.885361;
$location['iso'] = 'NL';
$location['country'] = 'Nederland';
$location['region'] = 'Noord-Holland';
$location['city'] = 'Amsterdam';
$location['street'] = 'Nieuwe Teertuinen';
$location['street_number'] = '25';
$location['postal_code'] = '1013 LV';

要将它作为对象返回,请将 get() 函数设置为 true: get(true)

限制结果按国家

要限制搜索结果仅包括来自一组预定义国家的情况,请使用 countries() 函数。它接受由 "ISO 3166-1 alpha-2" 定义的 iso 表示法国家名称。

扩展示例

try {
	$location = Location::coordinatesToAddress(['latitude' => 52.385288, 'longitude' => 4.885361])->get(true);

	if($error = Location::error()) {
		dd($error);
	}
}
catch(Exception $e) {
	dd($e->getMessage());
}

结果是默认模板,开始时为空,在调用过程中填充。因此,如果没有可用数据,该条目的结果将是 ""。每次调用后,脚本都会重置到其初始模板。

链式函数及其变量

其他函数

调试

使用 try catch,您已经可以看到您需要的。但除此之外,还有来自 Google API 的原始响应的缓存结果。请注意,这并不适用于 IP 请求。

$location = Location::coordinatesToAddress(['latitude' => 52.385288, 'longitude' => 4.885361])->get();
Location::response(); // results in raw api response