Using latitude and longitude coordinates to calculate the xyz position on earth in a three-dimensional environment (three

Exploring the wonders of three.js

I am currently working on rendering objects at specific geocoordinates on a large sphere. I am close to finding a solution, but I am struggling to determine the correct xyz position from latitude and longitude.

I have created a test case on jsfiddle with two coordinates

latlons = [[40.7142700,-74.0059700], [52.5243700,13.4105300]];

representing New York and Berlin.

Below is the function I am using to calculate xyz from latitude, longitude, and radius

function calcPosFromLatLonRad(lat,lon,radius){

// Attempt1
var cosLat = Math.cos(lat * Math.PI / 180.0);
var sinLat = Math.sin(lat * Math.PI / 180.0);
var cosLon = Math.cos(lon * Math.PI / 180.0);
var sinLon = Math.sin(lon * Math.PI / 180.0);
var rad = radius;
y = rad * cosLat * sinLon;
x = rad * cosLat * cosLon;
z = rad * sinLat;

// Other attempts...

   console.log([x,y,z]);
   return [x,y,z];
}

However, none of my attempts yield the correct xy positions (z is always accurate).

Could someone please assist me in finding the right approach? I am unsure where I am going wrong.

Here is the fiddle for experimentation

UPDATE: functional jsfiddle

Answer №1

Unfortunately, I cannot provide further explanation, but after experimenting with it, this solution works perfectly :)

function calculatePositionFromLatitudeLongitudeRadius(lat, lon, radius){
  
    var phi   = (90-lat)*(Math.PI/180);
    var theta = (lon+180)*(Math.PI/180);

    x = -(radius * Math.sin(phi)*Math.cos(theta));
    z = (radius * Math.sin(phi)*Math.sin(theta));
    y = (radius * Math.cos(phi));
  
    return [x,y,z];

}

Yeah, that's pretty cool, isn't it? And I'm still interested in finding a shorter equation.

Check out the working fiddle!

Answer №2

Here's a function that has been really helpful for me:

function calculatePositionFromLatLon(radius, latitude, longitude) {

  var sphericalCoordinates = new THREE.Spherical(
    radius,
    THREE.Math.degToRad(90 - longitude),
    THREE.Math.degToRad(latitude)
  );

  var vector = new THREE.Vector3();
  vector.setFromSpherical(sphericalCoordinates);

  console.log(vector.x, vector.y, vector.z);
  return vector;
}

calculatePositionFromLatLon(0.5, -74.00597, 40.71427);

Answer №3

Although this thread is quite old, I wanted to share an updated demo that was inspired by your previous one, now running on the latest version of three.js:

Check out the updated demo here!

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

What is the best way to implement a loading cursor when the Submit button is clicked?

Is there a way to incorporate a progress cursor into my code in order to notify the user to wait when they click the Submit button or the Upload Button while uploading multiple files? Below is an example of my form: <form action="" method="post" enct ...

nodejs promises and their implementation in loops

Currently delving into the realm of promises in nodejs, here's an example code snippet for you to peruse: The result when running the below code is as follows: test - 1 test - 2 test - 3 test - 4 var Q = require('q'); var promise = Q.when( ...

Displaying complex JSON data in an HTML format using JavaScript

How can I convert the second array of entities into an HTML format from the JSON data using a for loop or similar method? To access the necessary data, I currently use console.log(data.response[0].entities.urls); $(document).ready(function () { $.getJSO ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

What is the best way to update image CSS following a rotation using JavaScript?

Discover a neat CSS trick for always centering an image in a div, regardless of its size or aspect ratio. <style> .img_wrap { padding-bottom: 56.25%; width: 100%; position: relative; overflow: hidden; } #imgpreview { display: bl ...

Adjusting images of various sizes within a single row to fit accordingly

I am faced with a challenge of aligning a set of images on a webpage, each with varying heights, widths, and aspect ratios. My goal is to arrange them in a way that they fit seamlessly across the screen while ensuring their heights are uniform. Adjusting ...

How to activate a single element within a React array

I am currently working on developing a comment system similar to the one found on YouTube. In my setup, when I click on modify, all comments turn into input fields, but only the selected input should be modified. How can I trigger only the element I clicke ...

Is there a way to efficiently update specific child components when receiving data from websockets, without having to update each child individually?

Currently, my frontend requires updated data every 2 seconds. The process involves the frontend sending an init message to the backend over a websocket. Upon receiving this message, the backend initiates an interval to send the required data every 2 second ...

How can we show a div element when hovering over another element using css-in-js?

Is there a way to use material ui withStyles component in order to show information only on hover for a specific div? ...

unable to access various attributes in an angular directive

I have a particular HTML setup that effectively outlines each attribute's value through a distinct "attachment" directive. These values are located in the attrs list of said directive, which is within a modal file upload form. <p>For Testing Pu ...

Utilize dynamic global variables in React that are provided during runtime, making them unpredictable during the build process

I am currently developing an application for Overwolf, which you can find more information about at For this platform, applications are built using html/js and run in the Overwolf Browser. The browser provides access to the Overwolf API through a global v ...

Choose a phrase that commences with the term "javascript"

I need assistance in creating two unique regular expressions for the following purposes: To select lines that begin with 'religion'. Unfortunately, my attempt with /^religion/g did not yield any results. To match dates and their correspondi ...

Callback function not being triggered in Jquery's getJson method

I am currently faced with a javascript conundrum. Below is the snippet of code that I have been working on: $.get("categories/json_get_cities/" + stateId, function(result) { //code here }, 'json' ); ...

Error Arises When React Components Are Nested within Objects

I'm encountering a peculiar issue with my component. It works perfectly fine when retrieving data from State at a high level, but as soon as I try to access nested objects, it throws an error: "TypeError: Cannot read property 'name' of undef ...

Flipping a combination of CSS 3 and JavaScript cards will cause them to flip all together in unison

Hello! I came across a really cool card flip code that is IE compatible. I made some modifications to it and got it working, but there's one problem - instead of flipping the selected card, it flips all the cards. I tried modifying the JavaScript code ...

Whenever I attempt to generate a forecast utilizing a tensorflow.js model, I encounter the following error message: "Uncaught TypeError: Cannot read property 'length' of undefined."

I'm currently working on a project to build a website that utilizes a deep learning model for real-time sentiment analysis. However, I've encountered an issue when using the model.predict() function. It throws an error message: Uncaught TypeErro ...

Issue: ngModel: Unassignable Value

I am currently working on a piece of code that dynamically generates a drop-down list. My goal is to set the selected value using ng-repeat. In order to achieve this, I have implemented a function in ng-model. However, I am encountering an issue with the f ...

Quickly redesigning the appearance of file input using javascript and jquery. Seeking assistance to correct css issues on jsfiddle

Hey there, I've been working on styling the input[type="file"] element and could use some assistance. Like the saying goes, "One JSfiddle is worth 1000 words," so here's the link to my example: --- For more details, click here: http://jsfiddle.n ...

Rebalancing Rotation with Three.js

Currently, I am utilizing Three.js and my goal is to swap out an object in the scene with a new one while maintaining the same rotation as the one I removed. To achieve this, I take note of the rotation of the object I'm removing and then utilize the ...

.load() not triggering for images that are not in the cache - jquery

In Safari and Opera, the callback function of .load doesn't wait for uncached images to be fully loaded. With cached images, it works perfectly fine. The code may seem a little complicated, but I'll do my best to simplify it... So, here is my J ...