three.js绘制地图(平面、曲面)
作者:互联网
加载中国地图json数据
let loader = new THREE.FileLoader();
loader.load('model/chinaJson.json', function (data) {
let jsonData = JSON.parse(data);
initMap(jsonData); // 解析并绘制地图
});
绘制曲面地图
function initMap( chinaJson ) {
//创建一个空对象存放对象
map = new THREE.Object3D();
map.name = "china";
// 遍历省份构建模型
chinaJson.features.forEach( elem => {
// 新建一个省份容器:用来存放省份对应的模型和轮廓线
const province = new THREE.Object3D();
const coordinates = elem.geometry.coordinates;
coordinates.forEach( multiPolygon => {
multiPolygon.forEach( polygon => {
const lineMaterial = new THREE.LineBasicMaterial( { color: 0XF19553 } ); //0x3BFA9E
const positions = [];
const linGeometry = new THREE.BufferGeometry();
for (let i = 0; i < polygon.length; i ++) {
var pos = lglt2xyz( polygon[i][0], polygon[i][1] );//将经纬度转为3D坐标
positions.push( pos.x, pos.y, pos.z );
}
linGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
const line = new THREE.Line( linGeometry, lineMaterial );
province.add( line );
} );
} );
map.add( province );
map.scale.set(5,5,5);
map.rotation.y = Math.PI;
} );
chinaGroup.add(map);
chinaGroup.rotation.set(0.594, -0.348,-0.062);
scene.add(chinaGroup);
}
绘制平面地图
/**
* 描绘中国边界(平面)
需要传入Json数据
*/
function initMap(chinaJson)
{
//创建一个空对象存放对象
map = new THREE.Object3D();
map.name = "china";
//定义一个球体
//墨卡托投影转换 将经纬度转为3D坐标值
const projection = d3.geoMercator().center([104.0,37.5]).scale(80).translate([0,0]);
chinaJson.features.forEach((elem,index) => {
//定义一个省份3D对象
const province = new THREE.Object3D();
//每个的 坐标 数组
const coordinates = elem.geometry.coordinates;
//循环坐标数组
coordinates.forEach(multiPolygon =>{
multiPolygon.forEach( polygon =>{
const shape = new THREE.Shape();
const lineMaterial = new THREE.MeshBasicMaterial({
color:'white'
})
const lineGeometry = new THREE.Geometry();
for(let i = 0; i< polygon.length; i++)
{
const [x,y] = projection(polygon[i]);
if(i === 0)
{
shape.moveTo(x,-y);
}
shape.lineTo(x,-y);
lineGeometry.vertices.push(new THREE.Vector3(x,-y,4.01));
}
//拉伸厚度
const extrudeSettings = {
depth:4,
bevelEnabled:false
};
const geometry = new THREE.ExtrudeGeometry(shape,extrudeSettings);
const material = new THREE.MeshBasicMaterial({
color:'#02A1E2',
transparent:true,
opacity:0.6
});
const material1 = new THREE.MeshBasicMaterial({
color:'#3480C4',
transparent:true,
opacity:0.5
});
//this.mesh = new THREE.Mesh(geometry,[material,material1]);
const line = new THREE.Line(lineGeometry,lineMaterial);
// // 设置高度将省区分开来
// if (index % 2 === 0) {
// this.mesh.scale.set(1, 1, 1.2);
// }
// province.add(this.mesh);
province.add(line);
})
})
//将geo的属性放到省份模型中
province.properties = elem.properties;
if(elem.properties.contorid)
{
const [ x,y] = projection(elem.properties.contorid);
province.properties._centroid =[x,y];
}
map.add(province);
map.scale.set(0.2,0.2,0.2);
})
chinaGroup.add(map);
scene.add(chinaGroup);
}
标签:province,map,const,THREE,three,add,new,绘制地图,js 来源: https://www.cnblogs.com/huangchun/p/16661275.html