使用 Three.js + Three-Tile 实现地球场景与几何体

使用 Three.js + Three-Tile 实现地球场景与几何体

前言

在 3D 可视化开发中,Three.js 是一个强大的 WebGL 库,而 Three-Tile 是基于 Three.js 封装的地形渲染库。本文将通过 Vue3 的 <script setup> 方式,结合 Three.js 和 Three-Tile,在地理位置上实现地球场景,并添加几何体。


项目环境

  • Vue3 + Vite
  • Three.js 0.165.0
  • Three-Tile 0.9.0

安装依赖

css 复制代码
npm i three three-tile -S

核心功能实现

1. 创建 Vue 组件

xml 复制代码
<template>
  <div id="map"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import * as THREE from 'three';
import * as tt from 'three-tile';

// 创建球体模型
function createSphere(color) {
  const sphereGeometry = new THREE.SphereGeometry(2, 32, 32);
  const sphereMaterial = new THREE.MeshStandardMaterial({
    color,
    roughness: 0.2,
    metalness: 0.8,
    flatShading: true,
  });
  return new THREE.Mesh(sphereGeometry, sphereMaterial);
}

onMounted(() => {
  console.log(`three-tile v${tt.version} start!`);

  // 创建地图
  const map = tt.TileMap.create({
    imgSource: new tt.plugin.ArcGisSource(),
    demSource: new tt.plugin.ArcGisDemSource(),
  });

  // 地图旋转到xz平面
  map.rotateX(-Math.PI / 2);

  // 初始化场景
  const viewer = new tt.plugin.GLViewer("#map");

  // 地图添加到场景
  viewer.scene.add(map);

  // 青岛中心位置
  const centerPosition = map.geo2world(new THREE.Vector3(120.3826, 36.0671, 0));
  const cameraPosition = map.geo2world(new THREE.Vector3(120.3826, 36.0571, 0.9));

  // 飞行到目标位置
  viewer.flyTo(centerPosition, cameraPosition);

  // 添加红色立方体
  const geometry = new THREE.BoxGeometry(0.1, 0.1, 0.1);
  const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
  const cube = new THREE.Mesh(geometry, material);
  cube.position.copy(map.geo2world(new THREE.Vector3(120.3826, 36.0671, 0.5)));
  viewer.scene.add(cube);

  // 添加绿色球体
  const lonlat1 = new THREE.Vector3(120.32, 36.08, 1);
  const sphere1 = createSphere(0x00ff00);
  sphere1.position.copy(map.geo2world(lonlat1));
  viewer.scene.add(sphere1);

  // 限制相机高度,防止进入地下
  viewer.addEventListener("update", () => {
    tt.plugin.limitCameraHeight(map, viewer.camera);
  });
});
</script>

<style scoped>
html, body {
  background-color: #333;
  height: 400px;
  width: 100%;
  padding: 0;
  margin: 0;
  display: flex;
  overflow: hidden;
}

#map {
  flex: 1;
}
</style>

2. 主要功能解析

  1. 创建地图 :使用 three-tile 提供的 TileMap.create 方法加载 ArcGis 影像源和地形数据源。
  2. 相机定位 :通过 geo2world 将经纬度转换为 Three.js 世界坐标。
  3. 添加几何体:在地理上空添加立方体和球体。
  4. 相机高度限制:防止相机进入地下。

3. 效果展示

  • 红色立方体悬浮在地理上空
  • 绿色球体位于指定的经纬度位置

4. 总结

通过 Three.js + Three-Tile,成功地在地理位置上渲染了三维地形,并添加了几何体。


5. 参考文档


相关推荐
崔庆才丨静觅4 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60614 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了5 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅5 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅5 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅5 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅6 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊6 小时前
jwt介绍
前端
爱敲代码的小鱼6 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax