ThreeJS中的GeoJSON地图
const loader = new THREE.FileLoader();
loader.load("/geojson/china.json",(data) => {
const jsData = JSON.parse(data)
operationData(jsData)
})
function operationData(jsondata) {
// 全国信息
const features = jsondata.features;
features.forEach((feature) => {
// 单个省份 对象
const province = new THREE.Object3D();
// 地址
province.properties = feature.properties.name;
const coordinates = feature.geometry.coordinates;
const color = "#99ff99";
if (feature.geometry.type === "MultiPolygon") {
// 多个,多边形
coordinates.forEach((coordinate) => {
// console.log(coordinate);
// coordinate 多边形数据
coordinate.forEach((rows) => {
const mesh = drawExtrudeMesh(rows, color, projection1);
const line = lineDraw(rows, color, projection1);
// 唯一标识
mesh.properties = feature.properties.name;
province.add(line);
province.add(mesh);
});
});
}
if (feature.geometry.type === "Polygon") {
// 多边形
coordinates.forEach((coordinate) => {
const mesh = drawExtrudeMesh(coordinate, color, projection1);
const line = lineDraw(coordinate, color, projection1);
// 唯一标识
mesh.properties = feature.properties.name;
province.add(line);
province.add(mesh);
});
}
map.add(province);
});
scene.add(map);
}
function lineDraw(polygon, color, projection) {
const lineGeometry = new THREE.BufferGeometry();
const pointsArray = new Array();
polygon.forEach((row) => {
const [x, y] = projection(row);
// 创建三维点
pointsArray.push(new THREE.Vector3(x, -y, 9));
});
// 放入多个点
lineGeometry.setFromPoints(pointsArray);
// 生成随机颜色
const lineColor = new THREE.Color(
Math.random() * 0.5 + 0.5,
Math.random() * 0.5 + 0.5,
Math.random() * 0.5 + 0.5
);
const lineMaterial = new THREE.LineBasicMaterial({
color: lineColor,
});
return new THREE.Line(lineGeometry, lineMaterial);
}
// 根据经纬度坐标生成物体
function drawExtrudeMesh(polygon, color, projection) {
const shape = new THREE.Shape();
// console.log(polygon, projection);
polygon.forEach((row, i) => {
const [x, y] = projection(row);
// console.log(row, [x, y]);
if (i === 0) {
// 创建起点,使用moveTo方法
// 因为计算出来的y是反过来,所以要进行颠倒
shape.moveTo(x, -y);
}
shape.lineTo(x, -y);
});
// 拉伸
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: 5,
bevelEnabled: true,
});
// 随机颜色
const randomColor = (0.5 + Math.random() * 0.5) * 0xffffff;
const material = new THREE.MeshBasicMaterial({
color: randomColor,
transparent: true,
opacity: 0.5,
});
return new THREE.Mesh(geometry, material);
}
Powered by Waline v2.13.0