Converting latitude and longitude coordinates to pixels in a 3D environment with the help of three.js

I have geographical coordinates (latitude and longitude) for a specific location on a map. My goal is to represent this point in 3D space using the WebGL library three.js. How can I convert these latitude and longitude coordinates into their respective x, y, z values?

Answer №1

To accurately represent locations using latitude and longitude, you must decide which plane to project them onto. A simple approach is to assign X to longitude and Y to latitude, adjusting for scale as needed for precision. However, map projection can be much more complex overall. For further insights, explore responses on converting lat/lon to x/y coordinates. Hopefully, this information proves helpful.

Answer №2

After a thorough search for the most effective "three.js approach" to tackle this issue, I have decided to share it here for future reference. The following solution assumes that Y is oriented upwards:

const latLngToVector3 = (latLng, radius) => {
  const phi = Math.PI * (0.5 - (latLng.lat / 180));
  const theta = Math.PI * (latLng.lng / 180);
  const spherical = THREE.Spherical(radius || latLng.radius || 1, phi, theta);
  return new THREE.Vector3().setFromSpherical(spherical);
};

const vector3ToLatLng = (v3) => {
  const spherical = new THREE.Spherical().setFromVector3(v3);
  return {
    lat: 180 * (0.5 - (spherical.phi / Math.PI)),
    lng: 180 * (spherical.theta / Math.PI),
  };
};

// convert to x,y,z with radius = 1
const v3 = latLngToVector3({ lat: -16.8985, lng: 145.7134 });

// convert back to lat/lng
const latLng = vector3ToLatLng(v3);

To understand the underlying mechanisms, take a look at the Spherical.setFromvector3 and Vector3.setFromSpherical methods.

Answer №3

When you generate a fresh coordinate using pixels, it automatically converts to latitude and longitude.

let offsetX = 20;
let offsetY = 20;
let mapZoomLevel = 8;
const newPoint = new google.maps.Point(
     offsetX / Math.pow(2, mapZoomLevel),
     offsetY / Math.pow(2, mapZoomLevel)
);

From there, you can easily add the values of newPoint.x and newPoint.y to another set of coordinates.

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 preferred convention for defining AngularJS directives as "attributes" versus "elements"?

When creating Angular directives, I've noticed that some directives could also be defined as either an HTML element or an attribute. I'm curious to know what the community convention is for choosing between the two, and the reasons behind it. Fo ...

Pass the value from JavaScript to PHP

I am looking to insert a JavaScript value into PHP: var temp = $('#field_id').val().charAt(0); The 'temp' variable returns values ranging from 1 to 4. var value = "<?php echo $variable[temp]['id']; ?>"; How can I re ...

Launch the jQuery Fancybox on a separate webpage

I am facing an issue where I have a link in my index.html page and I need it to open a div located in another page named index2.html, but for some reason, it is not working. This is the code I currently have: Link in index.html <a href="#modal" id="o ...

What is the proper way to reconnect to a socket using an AngularJS service?

I have encountered an issue while writing an AngularJS app. My application relies on a socket connection to retrieve data consistently, so I created a factory as shown below: var Service = {}; var ws = new WebSocket("url"); var timer; Service.onMessage = ...

Gradient transition effect changing background color from bottom to top

I am facing an issue where I have a block and I want the background color to animate from bottom to top on hover. Can you please help me identify what is causing this problem? Your assistance is greatly appreciated. .right-block--wrapper { backgroun ...

What is the best way to divide the results of an array into two separate slides

I have a challenge where I need to split an array with over 50 entries into multiple slides, displaying only 14 entries per slide. I've attempted the following code: <div class="mySlides fade"> <div class='content'> ...

Under what circumstances would window.location fail to function in a web browser? (excluding disabled JavaScript)

Is there a scenario where window.location may not function properly? I have considered that certain older versions of Internet Explorer may block the javascript redirect due to security restrictions. Can anyone confirm this? Are there any specific browse ...

What is the most efficient way to arrange a table using one-time binding in angularJS while ensuring optimal modal performance?

My ng-repeat loop has clickable headers for sorting, but once it reaches around 150 elements and 8000+ watchers, extreme latency occurs. Speed can be increased using one-time binding, but this causes the loss of sorting functionality. <table class="tab ...

Is there a way for me to retrieve the values of <td name="pname"> when the Edit button is

When the button is clicked, I use jQuery to add items in a td that I have created. $("#ddproduct").click(function () { $('#prodcuttable tr:last').after('<tr><td name="pname">' + prodName + '</td> <t ...

Difference in values of $(document).height() as compared to $(document).scrollTop() added to $(window).height()

I am currently working on a project where I need to detect when an element enters the view in order to make it fade in. My initial approach was to track the element's vertical position on the page and trigger the fade-in effect when the scroll value w ...

Executing a PHP function from a separate PHP file with the onClick event in PHP

Within my two php files, 1.php and 2.php, they are linked using the require function. In php.1, there is a qr code created with the following snippet: <img src="http://chart.googleapis.com/chart?chs=125x125&cht=qr&chl=<?php echo $_jattu; ?&g ...

The select2 plugin seems to be having trouble recognizing the Li click functionality

I have a select menu that is using the select2 plugin. I am trying to add a class to the <select> element when a menu option is clicked, but it doesn't seem to be working as expected even after testing with an alert. https://jsfiddle.net/ysm4qh ...

Loading Images Dynamically in React with JSON Fetching

Here's the issue I'm facing: Below is a JSON object containing information about images: const imagesData = [ { "imagepath": "./images/a.jpg", "title": "Red Car", "uploadDate": "2 May 2020", "index": "0" } ...

Adjusting a Swiper JS parameter on the fly

Currently, I am attempting to dynamically adjust the eventsTarget within the mousewheel object in Swiper based on changes to a data property using Vue.js. Specifically, when disableBodyScroll is set to true, the carousel should scroll via eventsTarget:html ...

Exploring Netbeans 7.3 for Enhanced JavaScript Autocomplete with Parameters

Ever since the upgrade to netbeans 7.3, I've encountered an issue where netbeans no longer automatically provides me with parameter names. For instance, When I see "methodA(param1, param2) xxx.js" in the autocomplete pop-up, clicking on it or pressi ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

Challenges with bcryptjs and MySQL

I am facing an issue while trying to save a user in the database and create a hash of their password to save instead of the actual password. However, every attempt I make results in a RangeError: Maximum call stack size exceeded. Below is the User code sn ...

After a certain period of time, the NodeJs exec() function ceases to create additional

I am in the process of developing a BLE scan module on nodeJs using Bluez. Below is the code snippet I have implemented: exec('sudo hcitool lescan --duplicates &', function (error, stdout, stderr) { }); exec('sudo hcitool lescan --dupl ...

Tips for preventing the creation of .d.ts.map files while using tsc to exclusively generate declaration files

When I create a build using tsup, I encounter numerous errors with the dts option. The official tsup documentation also mentions that typescript declarations generated by tools other than tsc may not be perfect. As a result, I have decided to use tsc for ...

Having difficulty making my directive function in Angular

I'm encountering an issue with my directive not working properly. I suspect that I may have registered it incorrectly, but I can't seem to figure out the mistake. Could it be related to the naming convention? Here's the code snippet in quest ...