sjaakp/yii2-spatial

支持MySQL空间数据的Yii2 ActiveRecord

安装次数: 55,077

依赖者: 1

建议者: 0

安全: 0

星标: 17

关注者: 4

分支: 8

开放性问题: 6

类型:yii2-extension

1.1.2 2024-06-29 13:48 UTC

This package is auto-updated.

Last update: 2024-08-29 14:07:31 UTC


README

Latest Stable Version Total Downloads License

ActiveRecord带有空间属性。在查找后,这些属性从MySQL内部格式转换为GeoJSON格式,在存储之前相反。

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

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

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

安装

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

"sjaakp/yii2-spatial": "*"

或者运行

composer require sjaakp/yii2-spatial "*"

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

用法

简单地将sjaakp\spatial\ActiveRecord用作模型的基类,如下所示

<?php

use sjaakp\spatial\ActiveRecord;

class MySpatialModel extends ActiveRecord
{
    // ...
}

注意:如果在sjaakp\spatial\ActiveRecord派生类中重写find(),请确保返回一个sjaakp\spatial\ActiveQuery而不是一个“普通”的yii\db\ActiveQuery

ActiveRecord方法

featureProperties()

public function featureProperties($field, $geometry)

重写此函数以将属性添加到GeoJSON编码的属性。

  • $field是属性名称。
  • $geometry是一个包含GeoJSON信息的数组,类似于解码后的JSON。
  • 返回:arrayproperty => value

默认实现将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
  • 返回:$this

示例用法

$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找到一个非常微妙的错误。