js、mysql生成随机经纬度坐标的函数

//JS版本:生成以center为坐标中心的radius范围内的count个坐标点位数据
//distance值越大,生成的坐标点位越集中在坐标中心
function generateRandomCoordinates(center, radius, count, distance = 6500) {
						const lngCenter = center[0]; // 中心经度
						const latCenter = center[1]; // 中心纬度
						const coordinates = []; // 存储生成的经纬度数据

						for (let i = 0; i < count; i++) {
							// 生成指定范围内的随机距离(以米为单位)
							const randomDistance = Math.random() * radius;

							// 将随机距离转换为度数
							const distanceInDegrees = randomDistance / distance; // 每一度的大致距离

							// 生成随机角度(弧度)
							const randomAngle = Math.random() * 2 * Math.PI;

							// 计算经度和纬度的偏移量
							const lngOffset = distanceInDegrees * Math.cos(randomAngle);
							const latOffset = distanceInDegrees * Math.sin(randomAngle);

							// 计算新点的经度和纬度
							const lng = lngCenter + lngOffset;
							const lat = latCenter + latOffset;

							// 将经纬度数据添加到结果数组
							coordinates.push([lng, lat, 1]);
						}

						return coordinates;
					}

//调用
var t = generateRandomCoordinates([118.337569, 32.338458], 500, 100);
-- MYSQL版本

DELIMITER //

CREATE FUNCTION generateRandomCoordinates(
    center_lng DECIMAL(9,6),
    center_lat DECIMAL(8,6),
    radius FLOAT,
    count INT,
    distance FLOAT
)
RETURNS TEXT
BEGIN
    DECLARE i INT DEFAULT 0;
    DECLARE randomDistance FLOAT;
    DECLARE distanceInDegrees FLOAT;
    DECLARE randomAngle FLOAT;
    DECLARE lngOffset FLOAT;
    DECLARE latOffset FLOAT;
    DECLARE lng DECIMAL(9,6);
    DECLARE lat DECIMAL(8,6);
    DECLARE coordinates TEXT DEFAULT '';

    WHILE i < count DO
        -- 生成指定范围内的随机距离(以米为单位)
        SET randomDistance = RAND() * radius;

        -- 将随机距离转换为度数
        SET distanceInDegrees = randomDistance / distance;

        -- 生成随机角度(弧度)
        SET randomAngle = RAND() * 2 * PI();

        -- 计算经度和纬度的偏移量
        SET lngOffset = distanceInDegrees * COS(randomAngle);
        SET latOffset = distanceInDegrees * SIN(randomAngle);

        -- 计算新点的经度和纬度
        SET lng = center_lng + lngOffset;
        SET lat = center_lat + latOffset;

        -- 将经纬度数据添加到结果字符串
        SET coordinates = CONCAT(coordinates, IF(coordinates = '', '', ','), lng, ',', lat);

        SET i = i + 1;
    END WHILE;

    RETURN coordinates;
END //

DELIMITER ;





-- 调用
SELECT generateRandomCoordinates(112.3369, 33.38, 6000, 100, 6500);

注:以上内容根据业务测试需要,使用chartgpt生成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值