roman-franko/yii2-spatial

支持 MySQL 空间数据的 Yii2 ActiveRecord

安装: 20

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 0

分叉: 8

类型:yii2-extension

v1.0.3 2023-10-21 04:50 UTC

This package is auto-updated.

Last update: 2024-09-21 06:46:24 UTC


README

具有空间属性的 ActiveRecord。这些属性在查找时从内部 MySQL 格式 转换为 GeoJSON 格式,在存储之前反之亦然。

Yii-spatial 还可以用于查找与给定位置最近的模型或模型。

注意,此扩展仅适用于 MySQL 或 MariaDB 数据库。

版本 1.1.0 与 MySQL 5.7 和 MariaDB 10.3 兼容。

安装

使用 Composer 安装 Yii2-spatial。在您的 composer.json 文件的 require 部分中添加以下内容

"romanfranko/yii2-spatial": "*"

或者运行

composer require romanfranko/yii2-spatial "*"

您可以通过 下载 ZIP 格式的源代码 来手动安装 Yii2-spatial

使用方法

只需将 romanfranko\spatial\ActiveRecord 作为基类用于您的模型,如下所示

<?php

use romanfranko\spatial\ActiveRecord;

class MySpatialModel extends ActiveRecord
{
    // ...
}

注意:如果在一个 romanfranko\spatial\ActiveRecord 派生类中覆盖 find(),请确保返回一个 romanfranko\spatial\ActiveQuery 而不是一个 '普通' 的 yii\db\ActiveQuery

ActiveRecord 方法

featureProperties()

public function featureProperties($field, $geometry)

覆盖此函数以向 GeoJSON 编码的属性添加属性。

  • $field 是属性名称。
  • $geometry 是包含 GeoJSON 信息的数组,如解码的 JSON。

默认实现添加了 ActiveRecord 的主键作为属性 'id'

ActiveQuery 方法

nearest()

public function nearest($from, $attribute, $radius)

修改查询,使其找到由 $from 给定的点最近的一个或多个模型。

  • $from - string|array
    • string:搜索 PointFeature 的 GeoJSON 表示。
    • array:形式为 [<lng>, <lat>] 的位置(两个 float)。
  • $attribute - string 模型中 Point 的属性名称。
  • $radius - number 搜索半径(公里)。默认 100

示例用法

$here = [4.9, 52.3];     // longitude and latitude of my place

$here2 = '{"type":"Point","coordinates":[4.9,52.3]}';	// another representation
 

$nearestModel = <model>::find()->nearest($here, <attributeName>, 200)->one();    // search radius is 200 km

$fiveNearestModels =  <model>::find()->nearest($here, <attributeName>)->limit(5)->all();	// search radius is 100 km (default)

$dataProvider = new ActiveDataProvider([ 'query' => <model>::find()->nearest($here, <attributeName>) ]);

感谢

  • fpolito 找到一个非常微妙的错误。