当前位置:网站首页>Threejs realizes the drawing of the earth, geographical location annotation, longitude and latitude conversion of world coordinates threejs coordinates
Threejs realizes the drawing of the earth, geographical location annotation, longitude and latitude conversion of world coordinates threejs coordinates
2022-07-05 04:00:00 【Zuo Ben】
1, Introduce
This example uses r95 edition Three.js library .
Main functions : Draw the earth and geographical location for annotation
The renderings are as follows :
2, Main description
Prepare a map , Create a sphere and map it , Convert the longitude and latitude of the geographical location into threejs The world coordinates of , And mark it .
Create the earth , Part of the code is as follows :
// Create the earth radius 100
function createEarth() {
var earthGeo = new THREE.SphereGeometry(radius, 50, 50);
var earthMater = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('assets/earth/earth3.jpg'),
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
blending: THREE.AdditiveBlending,
opacity: 0.8,
color: 0x03d98e
});
var earthMesh = new THREE.Mesh(earthGeo, earthMater);
scene.add(earthMesh)
}
Longitude and latitude are converted into threejs coordinate ( Also called right-hand coordinate system )
phi It's the azimuth ( level ) The angle inside , Range 0~360 degree ,theta It's the pitch plane ( Vertical plane ) The angle inside , Range 0~180 degree 、 It's two parameters in the space polar coordinate system , And analogy in Cartesian coordinates xyz
threejs Implement transformation , The code is as follows :
// Coordinate transformation ,
function createPosition(lnglat) {
let spherical = new THREE.Spherical
spherical.radius = radius;
const lng = lnglat[0]
const lat = lnglat[1]
const theta = (lng + 90) * (Math.PI / 180)
const phi = (90 - lat) * (Math.PI / 180)
spherical.phi = phi; // phi It's the azimuth ( level ) The angle inside , Range 0~360 degree
spherical.theta = theta; // theta It's the pitch plane ( Vertical plane ) The angle inside , Range 0~180 degree
let position = new THREE.Vector3()
position.setFromSpherical(spherical)
return position
}
3, Source code
<!DOCTYPE html>
<html>
<head>
<title>Threejs Realize drawing the earth , Geographical location annotation - Longitude and latitude transform world coordinates </title>
<script type="text/javascript" src="libs/three.js"></script>
<script type="text/javascript" src="libs/OrbitControls.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="dom"></div>
<script type="text/javascript">
var camera;
var renderer;
var radius = 100; // Earth radius
var areas = [{
name: " China ",
position: [116.20, 39.55]
}, {
name: " Central African Republic ",
position: [18.35, 4.23]
}, {
name: " Chile ",
position: [-70.40, -33.24]
}, {
name: " Chad ",
position: [14.59, 12.10]
}, {
name: " Zambia ",
position: [28.16, -15.28]
}, {
name: " Vietnam ",
position: [105.55, 21.05]
}, {
name: " Jordan ",
position: [35.52, 31.57]
}, {
name: " The British Virgin Islands ",
position: [-64.37, 18.27]
}, {
name: " The British ",
position: [-0.05, 51.36]
}];
function init() {
// Create a scene , It will contain all our elements , Like an object , Cameras and lights .
var scene = new THREE.Scene();
var urls = [
'assets/textures/cubemap/flowers/posx.jpg',
'assets/textures/cubemap/flowers/negx.jpg',
'assets/textures/cubemap/flowers/posy.jpg',
'assets/textures/cubemap/flowers/negy.jpg',
'assets/textures/cubemap/flowers/posz.jpg',
'assets/textures/cubemap/flowers/negz.jpg'
];
var cubeLoader = new THREE.CubeTextureLoader();
// scene.background = cubeLoader.load(urls);
// Create a camera , It defines where we are looking
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
// Aim the camera at the center of the scene
camera.position.z = 500;
camera.lookAt(scene.position);
var orbit = new THREE.OrbitControls(camera);
// Create a renderer and set the size ,WebGLRenderer The computer graphics card will be used to render the scene
renderer = new THREE.WebGLRenderer({
antialias: true,
logarithmicDepthBuffer: true,
});
renderer.setSize(window.innerWidth, window.innerHeight);
// scene.add(new THREE.AmbientLight(0x666666));
var ambientLight = new THREE.AmbientLight("#ffffff", 1);
scene.add(ambientLight);
// Display the coordinate axis on the screen
var axes = new THREE.AxisHelper(radius);
scene.add(axes);
// Add planes to the scene
var plane = createPlaneGeometryBasicMaterial();
// scene.add(plane);
// initSphere(10, 0, 10);
createEarth();
createAreaPoint();
var rs = coordinateWorldTurnScreen(10, 0, 10);
var div = document.createElement('div');
div.innerHTML = ' state ';
div.style.padding = '5px';
div.style.position = 'absolute';
div.style.backgroundColor = 'rgba(155,0,155,0.8)';
document.body.appendChild(div);
div.style.left = rs.x + "px";
div.style.top = rs.y + "px";
console.log(rs)
// Add the output of the renderer to HTML Elements
document.getElementById("dom").appendChild(renderer.domElement);
// Start animation
renderScene();
/**
* Create the ground and add materials
* wrapS Attributes define the texture along x Axial behavior , and warpT Attributes define the texture along y Axial behavior .
* Three.js The following two options are provided for these attributes :
* ·THREE.RepeatWrapping Allow the texture to repeat itself .
* ·THREE.ClampToEdgeWrapping Is the default value of the attribute .
* The property value is THREE.ClampToEdgeWrapping when , Then the whole texture will not repeat , Only the pixels at the edge of the texture will be repeated to fill the remaining space .
*/
function createPlaneGeometryBasicMaterial() {
var textureLoader = new THREE.TextureLoader();
var cubeMaterial = new THREE.MeshStandardMaterial({
map: textureLoader.load("assets/textures/stone/cd.jpg"),
});
cubeMaterial.map.wrapS = THREE.RepeatWrapping;
cubeMaterial.map.wrapT = THREE.RepeatWrapping;
cubeMaterial.map.repeat.set(8, 8)
// Create the ground plane and set the size
var planeGeometry = new THREE.PlaneGeometry(100, 100);
var plane = new THREE.Mesh(planeGeometry, cubeMaterial);
// Set the plane position and rotate
plane.rotation.x = -0.5 * Math.PI;
plane.position.x = 0;
plane.position.z = 0;
return plane;
}
// World coordinates to screen coordinates
function coordinateWorldTurnScreen(x, y, z) {
let world_vector = new THREE.Vector3(x, y, z);
let vector = world_vector.project(camera);
let halfWidth = window.innerWidth / 2,
halfHeight = window.innerHeight / 2;
return {
x: Math.round(vector.x * halfWidth + halfWidth),
y: Math.round(-vector.y * halfHeight + halfHeight)
}
}
// Create the earth radius 100
function createEarth() {
var earthGeo = new THREE.SphereGeometry(radius, 50, 50);
var earthMater = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('assets/earth/earth3.jpg'),
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
blending: THREE.AdditiveBlending,
opacity: 0.8,
color: 0x03d98e
});
var earthMesh = new THREE.Mesh(earthGeo, earthMater);
scene.add(earthMesh)
}
function createAreaPoint() {
// sphere
let sphereGeom = new THREE.SphereGeometry(1, 20, 20),
sphereMat = new THREE.MeshBasicMaterial({
color: 0x03d98e,
wireframe: true
})
let sphere = new THREE.Mesh(sphereGeom, sphereMat)
scene.add(sphere)
// Landmarks and light cones
for (let i = 0, length = areas.length; i < length; i++) {
const position = createPosition(this.areas[i].position)
createHexagon(position); // landmark
}
}
// Coordinate transformation ,
function createPosition(lnglat) {
let spherical = new THREE.Spherical
spherical.radius = radius;
const lng = lnglat[0]
const lat = lnglat[1]
const theta = (lng + 90) * (Math.PI / 180)
const phi = (90 - lat) * (Math.PI / 180)
spherical.phi = phi; // phi It's the azimuth ( level ) The angle inside , Range 0~360 degree
spherical.theta = theta; // theta It's the pitch plane ( Vertical plane ) The angle inside , Range 0~180 degree
let position = new THREE.Vector3()
position.setFromSpherical(spherical)
return position
}
// Create landmark markers
function createHexagon(position) {
var hexagon = new THREE.Object3D()
let hexagonLine = new THREE.CircleGeometry(4, 6)
let hexagonPlane = new THREE.CircleGeometry(3, 6)
let vertices = hexagonLine.vertices
vertices.shift() // The first node is the central point
let material = new THREE.MeshBasicMaterial({
color: 0xffff00,
side: THREE.DoubleSide,
opacity: 0.5
})
let circleLine = new THREE.LineLoop(hexagonLine, material)
let circlePlane = new THREE.Mesh(hexagonPlane, material)
circleLine.position.copy(position)
circlePlane.position.copy(position)
circlePlane.lookAt(new THREE.Vector3(0, 0, 0))
circleLine.lookAt(new THREE.Vector3(0, 0, 0))
hexagon.add(circleLine)
hexagon.add(circlePlane)
scene.add(hexagon);
}
// Initial sphere
function initSphere(x, y, z) {
var geometry = new THREE.SphereGeometry(1, 100, 100); // Sphere geometry
var material = new THREE.MeshBasicMaterial({
color: 0xffff00
}); // Grid base material
var sphere = new THREE.Mesh(geometry, material);
sphere.position.x = x;
sphere.position.y = y;
sphere.position.z = z;
scene.add(sphere);
}
function renderScene() {
orbit.update();
// Use requestAnimationFrame Function to render
requestAnimationFrame(renderScene);
renderer.render(scene, camera);
}
// Rendered scenes
renderer.render(scene, camera);
}
window.onload = init;
// Modify the scene as the form changes
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Listen for form resizing events
window.addEventListener('resize', onResize, false);
</script>
</body>
</html>
If you need a complete code, please leave a message or contact me on wechat :1171053128
边栏推荐
- ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
- 【刷题】BFS题目精选
- How does the applet solve the rendering layer network layer error?
- The order of LDS links
- 天干地支纪年法中为什么是60年一个轮回,而不是120年
- 基于TCP的移动端IM即时通讯开发仍然需要心跳保活
- [C language] address book - dynamic and static implementation
- 技术教程:如何利用EasyDSS将直播流推到七牛云?
- [software reverse - basic knowledge] analysis method, assembly instruction architecture
- 为什么百度、阿里这些大厂宁愿花25K招聘应届生,也不愿涨薪5K留住老员工?
猜你喜欢
Clickhouse物化视图
Rust blockchain development - signature encryption and private key public key
[array]566 Reshape the matrix - simple
De debugging (set the main thread as hidden debugging to destroy the debugging Channel & debugger detection)
An elegant program for Euclid‘s algorithm
Pyqt5 displays file names and pictures
On the day 25K joined Tencent, I cried
MindFusion.Virtual Keyboard for WPF
Redis source code analysis: redis cluster
【web审计-源码泄露】获取源码方法,利用工具
随机推荐
【web审计-源码泄露】获取源码方法,利用工具
【看完就懂系列】一文6000字教你从0到1实现接口自动化
speed or tempo in classical music
Containerd series - what is containerd?
An elegant program for Euclid‘s algorithm
Is there a sudden failure on the line? How to make emergency diagnosis, troubleshooting and recovery
优先使用对象组合,而不是类继承
C # use awaiter
Clickhouse synchronization MySQL (based on materialization engine)
面试字节,过关斩将直接干到 3 面,结果找了个架构师来吊打我?
Assembly - getting started
Google Chrome CSS will not update unless the cache is cleared - Google Chrome CSS doesn't update unless clear cache
[brush questions] BFS topic selection
Some enterprise interview questions of unity interview
The order of LDS links
Rome链分析
Redis之Jedis如何使用
Phpmailer reported an error: SMTP error: failed to connect to server: (0)
UE4 DMX和grandMA2 onPC 3.1.2.5的操作流程
Anti debugging (basic principles of debugger Design & NT NP and other anti debugging principles)