最近项目中用到地理坐标,所以mysql就使用了point类型,当然查询的时候可以用mysql的空间函数实现,ST_X(p):获取点 p 的 X 坐标,ST_Y(p):获取点 p 的 Y 坐标。
但我觉得还是用php实现好点,让它自动转换,因为我用的thinkphp,在 ThinkPHP 框架中,get+字段名+Attr 是一种用于定义模型属性访问器(Accessor)的方法。属性访问器允许你在获取模型属性时对数据进行自定义处理。这种机制通常用于格式化数据、转换数据类型或进行其他数据处理操作。
我的location字段保存了地理坐标,所以我在模型层定义了一个getLocationAttr方法,让它自动转换,实现方法如下,希望有相同需求的人可以用上
public function getLocationAttr($point): array
{
$offset = 4; // 跳过前 4 个字节
$byteOrder = ord($point[$offset]);
$srid = unpack($byteOrder === 1 ? 'V' : 'N', substr($point, $offset + 1, 4))[1]; // 使用 'V' 解包小端序,'N' 解包大端序
if ($srid !== 1) { // 1 表示 Point 类型
return [
'longitude' => null,
'latitude' => null
];
}
$offset += 5; // 1 字节字节序 + 4 字节几何类型
if ($byteOrder === 1) {
$x = unpack('d', substr($point, $offset, 8))[1];
$y = unpack('d', substr($point, $offset + 8, 8))[1];
} else { // 大端序
$x = unpack('d', strrev(substr($point, $offset, 8)))[1];
$y = unpack('d', strrev(substr($point, $offset + 8, 8)))[1];
}
return [
'longitude' => $x,
'latitude' => $y,
];
}
查询出来location自动转换