概要
小工具(TypeScript+Vue3+Turf),可生成指定数量的GeoJson格式矢量点(Point)数据,属性包括name、color、rotation、opacity等(随机值),需要引入Turf。
<script setup lang="ts">
import { ref, onMounted } from "vue"
import * as turf from '@turf/turf'
// 输入期望生成数量
const inputValue = ref(10000)
// GeoJson对象
let geo = ref({
type: "FeatureCollection",
features: []
})
// 程序入口
function start() {
const data = turf.randomPoint(inputValue.value, { bbox: [-180, -90, 180, 90] })
data.features.forEach(creatGeo)
downloadFile(geo.value)
}
//数据生成
function creatGeo(turfFeature: turf.helpers.Feature<turf.helpers.Geometry>) {
let coordinate = turfFeature.geometry.coordinates
// 生成 0~0.24 的随机数
const englishType = parseFloat((Math.random() * 0.24).toFixed(2))
// 生成 0~1 的随机数
const rotation = parseFloat((Math.random()).toFixed(2))
// 生成 0~1 的随机数,精确到 1 位小数
const opacity = parseFloat(Math.random().toFixed(1))
// 生成两位数的随机数字字符串(编号)
// 测试数据 englishType只生成第一列编号
const getRandomNumberString = () => {
let x = parseFloat((Math.random() < 0.5 ? englishType * 2 : englishType * 2 + 0.01).toFixed(2)) * 100
return x.toFixed(0).padStart(2, '0')
}
const name = `${getRandomNumberString()}00`
// 期望生成完整编号用下面的
// const getRandomNumberString = () => {
// const randomNumber = Math.floor(Math.random() * 49) + 1;
// return randomNumber.toString().padStart(2, '0')
// }
// const name = `${getRandomNumberString()}${getRandomNumberString()}`
// 随机颜色代号
const getRandomNumber = () => {
const numbers = [0, 1, 2, 3];
const randomIndex = Math.floor(Math.random() * numbers.length);
return numbers[randomIndex];
};
// 随机RGB颜色
// const getRandomRGBA = () => {
// const r = Math.floor(Math.random() * 256); // 生成 0 到 255 之间的随机整数
// const g = Math.floor(Math.random() * 256);
// const b = Math.floor(Math.random() * 256);
// return `rgba(${r}, ${g}, ${b})`;
// }
const color = getRandomNumber();
let obj = {
"type": "Feature",
"properties": {
"rotation": rotation,
"name": name,
"englishType": englishType,
"opacity": opacity,
"color": color
},
"geometry": {
"coordinates": coordinate,
"type": "Point"
}
}
geo.value.features.push(obj)
}
// 下载数据
function downloadFile(json: any) {
let jsonString = JSON.stringify(json)
// 创建 Blob 对象
var blob = new Blob([jsonString], { type: "application/json" });
// 创建下载链接
var downloadLink = document.createElement("a");
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = "geoJson.json";
// 下载
document.body.appendChild(downloadLink);
downloadLink.click();
// 清理链接
document.body.removeChild(downloadLink);
}
onMounted(() => {
start()
})
</script>
数据样例:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"rotation": 0.01,
"name": "3500",
"englishType": 0.17,
"opacity": 0.4,
"color": 2
},
"geometry": {
"coordinates": [
-15.183829600909434,
63.574883642733454
],
"type": "Point"
}
}
}