Creating an HTML element within a three.js globe

I have a globe created using three.js

Reference:

I am trying to display an HTML div at a specific latitude/longitude on the globe. Can someone guide me on how to position the div at a particular lat/long?

What I've attempted: I'm currently stuck on converting latitude and longitude to screen coordinates.

Here is a snippet of my JavaScript code:

            var camera, scene, renderer, controls, root_object = 0, mesh;
            var uniform_color = true, uniform_height = true, extrusion_amount = 5.0;
            var helper_1, helper_2;
            var radius;
            init();
            animate();

        function _convertLatLonToVec3 (lat,lon) {
            lat =  lat * Math.PI / 180.0;
            lon = -lon * Math.PI / 180.0;
            return new THREE.Vector3( 
                Math.cos(lat) * Math.cos(lon), //rechts links invert
                Math.sin(lat),  // up down invert
                Math.cos(lat) * Math.sin(lon));
        }

        function InfoBox( city, mesh, radius, domElement )
        {
            var position = _convertLatLonToVec3( city.lat, city.lng ).multiplyScalar( radius );
            this.mesh = mesh;
            this.mesh.position.copy( position );

            this._screenVector = new THREE.Vector3(0,0,0);

            this.box = document.createElement( 'div' );
            this.box.innerHTML = city.name;
            this.box.className = "hudLabel";

            this.domElement = domElement;
            this.domElement.appendChild( this.box );

        }
        
        /* Additional code continues... */

Currently, the issue does not seem to be related to the functioning of globe_manipulator.

Answer №1

I decided to share this information in the form of an answer because it goes beyond the original purpose of the comments section.

To begin, you need to convert your Latitude and Longitude coordinates into a THREE.Vector3. You can achieve this by using the following function:

function transformLatLonToVector(lat, lon) {
    lat =  lat * Math.PI / 180.0;
    lon = -lon * Math.PI / 180.0;
    return new THREE.Vector3( 
        Math.cos(lat) * Math.cos(lon),
        Math.sin(lat),
        Math.cos(lat) * Math.sin(lon));
};

Once you have the Vector3, you can determine the position on your sphere (globe) by multiplying it with the radius:

var radius = 100;
var position = transformLatLonToVector(city.latitude, city.longitude).multiplyScalar(radius);

This represents your location in 3D space.

The next step involves calculating the screen position from the 3D position and updating the HTML Overlay box accordingly. Here is a summary of how it can be achieved:

var screenVector = new THREE.Vector3(0, 0, 0);
screenVector.copy(position);
screenVector.project(camera);

var posX = Math.round((screenVector.x + 1) * domElement.offsetWidth / 2 );
var posY = Math.round((1 - screenVector.y) * domElement.offsetHeight / 2 );

// Adjust the HTML overlay box
this.box.style.left = posX + 'px';
this.box.style.top =  posY + 'px';

This process needs to be repeated for every update, as makc utilizes Object3D for this purpose.

If you need further clarification, you can refer to this simple example: http://jsfiddle.net/qac19w5x/

https://i.stack.imgur.com/ZtoCa.png

For additional guidance, consider exploring this pre-made class created by makc: three-js-and-2d-overlays

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The image tag in HTML is unable to display as an image within the jQuery object

After converting the object "suggestion" to a string, I have data stored in the "sugestion" variable like this: {"value":"<img src=\"http://localhost/erp/assets/images/product/123.jpg\"> 123123123 t-shirt","data":"ABC098765"} Unfortunatel ...

Tips for integrating Apache Solr with Cassandra without using DataStax Enterprise (DSE)

Embarking on a new project, I find myself utilizing Cassandra as the chosen DBMS, with Apache Solr serving as the search engine and Node.js powering the server scripting language. While I am well-versed in Node.js, Cassandra and Solr are unfamiliar territ ...

The configuration error occurred for the `get` action due to an unexpected response. Instead of an object, an array was received

Despite numerous attempts, I am struggling to find a solution that works for me. In my Courses controller, I am using the Students service and Staff service to access my staff and student objects. My goal is to retrieve the staffs and students objects in o ...

When would this be required within JavaScript or Angular?

Being new to JavaScript, I have come across information stating that the value of this changes based on how a function is invoked. However, I am confused about when it is necessary to use this and when it is not. Some code examples I've seen utilize t ...

Steps for leveraging pdfMake with live data

Recently delving into Angular, I've been exploring the capabilities of pdfMake. While I successfully incorporated static data, I'm facing challenges when attempting to utilize dynamic data. Any guidance on how to achieve this would be greatly app ...

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

Setting up a textarea tooltip using highlighter.js

I'm experimenting with using highlighter.js within a textarea. I've customized their sample by substituting the p with a textarea enclosed in a pre tag (for right-to-left language settings). <div class="article" style="width: 80%; height: 80% ...

The jQuery datetimepicker fails to reflect changes made to the minDate property

I have encountered a datetimepicker object that was previously set up with the following configuration: $('#startDate').datetimepicker({ monthNames: DATE_TIME_MONTHS_NAMES, monthNamesShort: DATE_TIME_MONTHS_NAMES_SHORT, dayNames: DAT ...

The Autocomplete feature from the @react-google-maps/api component seems to be malfunctioning as it returns

I'm encountering some difficulties with the Autocomplete component in @react-google-maps/api. While Autocomplete is working and displaying options, clicking on an option fills the input box but I'm only getting 'undefined' from the Plac ...

Having trouble with innerHTML.value functionality?

Recently, I've been delving into creating a JavaScript program that fetches Wikipedia search results. Initially, everything seemed to be working fine as I was able to display the searched item using the alert() method. However, for some reason, it now ...

What is the best way to input information into my Google spreadsheet with React JS?

After using https://github.com/ruucm/react-google-sheets as a reference, I encountered a persistent gapi 404 error whenever I tried to run the code. It seems like the GitHub link might not exist, causing my app to fail. However, I could be mistaken. Is t ...

Conduct a text search within mongoDB to retrieve the corresponding reference document for every item stored in the collection

I am in the process of developing a search functionality for a collection of trips. This search feature will check if the trip includes specific city names (origin and destination). Each trip entry contains the user ID of the person who created it. The sea ...

There seems to be an issue with the functionality of $apply in angular when used in conjunction with form

I've encountered an issue with my code where the form submission doesn't work properly unless I wait a few milliseconds before submitting. The problem seems to be related to setting the value of a hidden field called paymentToken. My goal is to ...

Using AJAX/jQuery to populate a SelectList in an MVC view

I have a C# MVC application where I am dynamically populating a dropdown based on a selected date using AJAX/jQuery. The action called retrieves a list of items for the chosen date. The issue I'm facing is that I've previously rendered a partial ...

Converting a Javascript array to an NSArray in Xcode

As a complete beginner to Xcode and programming in general, I recently built an app using javascript and html and integrated it into Xcode. Currently, my main focus is on extracting multiple arrays from the html/javascript file and exporting them as a csv ...

The animation of the model I imported does not match what I created in Blender

After creating a simple object and animation in Blender involving bone rotation, I encountered an issue when importing it into Three.js. Despite the smooth animation resembling what was created in Blender, it appeared rougher and not properly skinned. htt ...

What will the relationships be like between the models using Sequelize?

Hello there, I'm seeking assistance in establishing the correct associations between models using Sequelize. In my project, I have three types of products, each with unique attributes as well as shared attributes. ...

How can we have a div stay at the top of the screen when scrolling down, but return to its original position when scrolling back up?

By utilizing this code, a div with position: absolute (top: 46px) on a page will become fixed to the top of the page (top: 0px) once the user scrolls to a certain point (the distance from the div to the top of the page). $(window).scroll(function (e) { ...

Tips for setting a unique JWT secret in next-auth for production to prevent potential issues

Is there a way to properly set a JWT secret in NextAuth.js v4 to prevent errors in production? I have followed the guidelines outlined in the documentation, but I am still encountering this warning message without any further explanation: [next-auth][warn] ...

Leveraging React Native to retrieve information from a promise in JSON format

After successfully fetching the JSON data, I now have an array. My question is how can I utilize the elements within this array in a React Native environment? Below is my current approach: export default function display() { const fetching = async() => ...