概要
小工具(TypeScript+Vue3+Turf),可生成指定数量的GeoJson格式矢量线(LineString)数据,属性包括name、color、opacity等(随机值),需要引入Turf。
<script setup lang="ts">
import { onMounted, ref } from "vue"
import * as turf from '@turf/turf'
// 期望生成的数量
const inputValue = ref(10000)
// GeoJson对象
let geo = ref({
type: "FeatureCollection",
features: []
})
// 入口
function start() {
const data = turf.randomLineString(inputValue.value, { bbox: [-180, -90, 180, 90], max_length: 1 })
data.features.forEach(creatGeo)
downloadFile(geo.value)
}
// 数据生成
function creatGeo(turfFeature: turf.helpers.Feature<turf.helpers.Geometry>) {
let coordinate = turfFeature.geometry.coordinates
// 透明度,精确到 1 位小数
const opacity = parseFloat(Math.random().toFixed(1))
// 随机名称
function generateRandomName() {
const adjectives = ["Big", "Small", "Crazy", "Brave", "Wild", "Gentle", "Silly", "Happy", "Lucky", "Wise"];
const nouns = ["Elephant", "Tiger", "Lion", "Monkey", "Dolphin", "Kangaroo", "Giraffe", "Penguin", "Owl", "Turtle"];
const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
return randomAdjective + " " + randomNoun;
}
const name = generateRandomName();
// 随机颜色
function getRandomColor() {
const letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
const color = getRandomColor()
let obj = {
"type": "Feature",
"properties": {
"name": name,
"opacity": opacity,
"color": color
},
"geometry": {
"coordinates": coordinate,
"type": "LineString"
}
}
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": {
"name": "Wild Monkey",
"opacity": 0.9,
"color": "#B011B9"
},
"geometry": {
"coordinates": [
[
-49.96371765347669,
41.845725108200355
],
[
-50.009347363386,
41.86656844603469
],
[
-49.813249591882986,
41.718594794912484
]
],
"type": "LineString"
}
},
]
}