ThreeJS实现简单的3D地图(含全部代码)

ThreeJS实现简单3D地图
该文章已生成可运行项目,

第一步:GeoJSON数据准备

1、地图数据大家可以从 阿里云DataV 处获取下载

2、geoJson的坐标需要进行墨卡托投影转换才能转换成平面坐标,这里需要用到d3(js库)

             // 墨卡托投影转换

          const projection = d3.geoMercator().center([119.08, 36.67]).scale(400).translate([0, 0]);

//上面.center([119.08, 36.67])里面的经纬度设置成地图中心城市的坐标系即可,其他参数可以不变

          const [centerX,centerY] = projection(city.properties.centroid);//将经纬度转换为平面坐标系数据

第二步:写代码(有点直白啦,哈哈哈···)

最终效果:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>山东省3D地图</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        #container {
            position: absolute;
            width: 100%;
            height: 100%;
        }
        #info {
            position: absolute;
            top: 10px;
            width: 100%;
            text-align: center;
            color: #fff;
            background-color: rgba(0, 0, 0, 0.5);
            padding: 5px;
            z-index: 100;
        }
        .label {
            color: #fff;
            font-family: 'Microsoft YaHei', sans-serif;
            font-size: 14px;
            font-weight: bold;
            text-shadow: 1px 1px 2px #000;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div id="container"></div>
    <div id="info">山东省3D地图 - 使用鼠标拖动查看,滚轮缩放</div>
    <!--使用外部cdn引入threejs库-->
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
    <!--这里是geojson数据,我改成了js文件引入的-->
    <script src="./static/js/geo/shandong.js"></script>
    <!--使用外部cdn引入d3库-->
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script>
        const meshes = [];
        // 初始化场景
        const scene = new THREE.Scene();
        scene.background = new THREE.Color(0x1a2b3c);
        
        // 初始化相机
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.z = 30;
        camera.position.y = 10;
        camera.position.x = -5;
        
        // 初始化渲染器
        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.getElementById('container').appendChild(renderer.domElement);

        
        // 添加光源
        const ambientLight = new THREE.AmbientLight(0x404040);//环境光
        scene.add(ambientLight);
        
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);//平行光
        directionalLight.position.set(1, 1, 1);
        scene.add(directionalLight);
        
        // 添加轨道控制
        const controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.enableDamping = true;
        controls.dampingFactor = 0.05;
        

           // 墨卡托投影转换
          const projection = d3.geoMercator().center([119.08, 36.67]).scale(400).translate([0, 0]);

        const cities = [];
        const colors = ['#08c1f8'];
        var i = 1;
    
        geo.features.forEach(city =>{
            const name  = city.properties.name;
            const [centerX,centerY] = projection(city.properties.centroid);
            const se =  colors[0];
            i++;
            const points = [];
            city.geometry.coordinates[0].forEach(value =>{
               // console.log(value);
                value.forEach(v=>{
                  const [x,y] = projection(v);
                  const point = new THREE.Vector2(x,-y);
                  points.push(point);
                })
             
            })
          
            const cityObject = {
                name:name,
                center:[centerX ,-centerY],
                points:points,
                color:se
            };
            
            cities.push(cityObject)

        })
        console.log(cities);


        
        // 创建山东省地图
        function createShandongMap() {
     
            const color = new THREE.Color();//默认是纯白色0xffffff。
            // 创建各市区
            cities.forEach(city => {
                const shape = new THREE.Shape(city.points);
                const geometry = new THREE.ExtrudeGeometry(shape, {
                    depth: 2,
                    bevelEnabled: false//倒角
                });
                
                const material = new THREE.MeshPhongMaterial({ 
                    color: color.set(city.color),
                    transparent: false,
                    opacity: 1
                });
                
                const mesh = new THREE.Mesh(geometry, material);
                meshes.push(mesh);
                scene.add(mesh);
                
                // 添加边界线
                const edges = new THREE.EdgesGeometry(geometry);
                const line = new THREE.LineSegments(
                    edges,
                    new THREE.LineBasicMaterial({ color:color.set(city.color), linewidth: 2 })
                );
                scene.add(line);
                
                // 添加城市名称标签
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                canvas.width = 128;
                canvas.height = 64;
                context.font = "bold 24px Microsoft YaHei";
                context.fillStyle = '#ffffff';
                context.textAlign = 'center';
                context.fillText(city.name, 64, 34);
                
                const texture = new THREE.CanvasTexture(canvas);
                const labelMaterial = new THREE.SpriteMaterial({ 
                    map: texture,
                    transparent: true
                });
                
                const label = new THREE.Sprite(labelMaterial);
                label.position.set(city.center[0],city.center[1], 2.5);
                label.scale.set(5, 2.5, 1);
                scene.add(label);

            });
            
           
        }
        
        // 创建地面
        function createGround() {
            const geometry = new THREE.PlaneGeometry(100, 100);
            const material = new THREE.MeshPhongMaterial({
                color: 0x2c3e50,
                side: THREE.DoubleSide
            });
            const ground = new THREE.Mesh(geometry, material);
            ground.rotation.x = Math.PI / 2;
            ground.position.y = -1;
            scene.add(ground);
        }
        
        // 初始化函数
        function init() {
            //createGround();
            createShandongMap();
            // 响应窗口大小变化
            window.addEventListener('resize', onWindowResize, false);
            
            // 开始动画循环
            animate();
   
        }
        
        // 窗口大小变化处理
        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        }
        
        // 动画循环
        function animate() {
            requestAnimationFrame(animate);// 递归调用自身以保持循环
            controls.update();
            renderer.render(scene, camera);
        }
       
        var prev = 0;
        //鼠标事件
        renderer.domElement.addEventListener('mousemove', function (event) {
            // .offsetY、.offsetX以canvas画布左上角为坐标原点,单位px
            const px = event.offsetX;
            const py = event.offsetY;
            //屏幕坐标px、py转WebGL标准设备坐标x、y
            //width、height表示canvas画布宽高度
            const x = (px / window.innerWidth) * 2 - 1; 
            const y = -(py / window.innerHeight) * 2 + 1;
            //创建一个射线投射器`Raycaster`
            const raycaster = new THREE.Raycaster();
            //.setFromCamera()计算射线投射器`Raycaster`的射线属性.ray
            // 形象点说就是在点击位置创建一条射线,射线穿过的模型代表选中
            raycaster.setFromCamera(new THREE.Vector2(x, y), camera);
            //.intersectObjects([mesh1, mesh2, mesh3])对参数中的网格模型对象进行射线交叉计算
            // 未选中对象返回空数组[],选中一个对象,数组1个元素,选中两个对象,数组两个元素
            const intersects = raycaster.intersectObjects(meshes);
            console.log("射线器返回的对象", intersects);

           
            // intersects.length大于0说明,说明选中了模型
            if (intersects.length > 0) {
                 // 选中模型的第一个模型,设置为红色
                intersects[0].object.material.color.set(0xff0000);
                if(meshes[prev] !== intersects[0].object){
                    meshes[prev].material.color.set('#08c1f8');
                 }

                 for(let i = 0;i<= meshes.length;i++){
                    if(meshes[i] == intersects[0].object){
                        prev = i;break;
                    }
                 }
             
            }else{
                 meshes[prev].material.color.set('#08c1f8');
            }
        })

         

       // 启动应用
        init();
    </script>
</body>
</html>

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值