|
发表于 2025-2-16 21:10:44
|
显示全部楼层
GPT给的mysql的方法
添加列
ALTER TABLE tc_positions
ADD COLUMN latitude_gps DOUBLE NULL AFTER latitude,
ADD COLUMN longitude_gps DOUBLE NULL AFTER longitude;
自定义函数
CREATE FUNCTION geoc_wgs84togcj02(geom POINT)
RETURNS POINT
DETERMINISTIC
BEGIN
DECLARE lon DOUBLE;
DECLARE lat DOUBLE;
DECLARE gcj_lon DOUBLE;
DECLARE gcj_lat DOUBLE;
SET lon = ST_X(geom);
SET lat = ST_Y(geom);
-- 在此处实现 WGS84 -> GCJ-02 的具体数学转换
-- 这里只是演示,用了一个简单的偏移,实际需要完整公式
SET gcj_lon = lon + 0.002;
SET gcj_lat = lat + 0.0018;
RETURN ST_GeomFromText(CONCAT('POINT(', gcj_lon, ' ', gcj_lat, ')'), 4326);
END;
创建触发器,自动转换
DELIMITER //
CREATE TRIGGER wgs84_to_gcj02_trigger
BEFORE INSERT ON tc_positions
FOR EACH ROW
BEGIN
DECLARE orig_longitude DOUBLE;
DECLARE orig_latitude DOUBLE;
DECLARE geom_point GEOMETRY;
DECLARE converted_geom GEOMETRY;
-- 1) 先保存原始 WGS84 坐标
SET orig_longitude = NEW.longitude;
SET orig_latitude = NEW.latitude;
-- 2) 构造一个 SRID=4326 的 POINT 对象
SET geom_point = ST_GeomFromText(
CONCAT('POINT(', orig_longitude, ' ', orig_latitude, ')'),
4326
);
-- 3) 调用自定义函数,将 WGS84 -> GCJ-02
SET converted_geom = geoc_wgs84togcj02(geom_point);
-- 4) 更新触发器中的 NEW 行
-- 4.1) 将转换后的 GCJ-02 坐标写入 longitude、latitude
SET NEW.longitude = ST_X(converted_geom);
SET NEW.latitude = ST_Y(converted_geom);
-- 4.2) 将原始坐标存入 latitude_gps、longitude_gps
SET NEW.longitude_gps = orig_longitude;
SET NEW.latitude_gps = orig_latitude;
END;
//
DELIMITER ;
观察了下 latitude_gps 和 longitude_gps 是转换后的坐标了
|
|