//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生成