Adjusting the view of the three.js camera

After exploring the Three.js globe example on github, I set out to create my own globe using some specific data. However, I am encountering difficulty in making the camera focus on a given coordinate.

I attempted to use a function to convert coordinates into points and adjust the camera position accordingly, but it seems to have no effect:

 function searchCountry(lat, lng){

    var phi = (90 - lat) * Math.PI / 180;
    var theta = (180 - lng) * Math.PI / 180;

    camera.position.x = 200 * Math.sin(phi) * Math.cos(theta);
    camera.position.y = 200 * Math.cos(phi);
    camera.position.z = 200 * Math.sin(phi) * Math.sin(theta);
    camera.lookAt(mesh.position);
}

The remaining code structure mirrors that of the globe example. I pass arguments from the index file as follows:

<select class="country">
   <option data-lat="33" data-lng="65">Afghanistan</option>
</select>

In addition:

jQuery(".country").change(function () {
    console.log(jQuery(".country :selected").data('lat'), jQuery(".country :selected").data('lng'));

    globe.searchCountry(jQuery(".country :selected").data('lat'), jQuery(".country :selected").data('lng'));
});

Despite successful echoing of values and conversions, the globe remains stationary without rotating to the specified coordinates. Furthermore, I am looking to implement a zoom feature within the rotate function for closer visualization upon rotation. Any suggestions or insights on enabling this functionality would be greatly appreciated.

Answer №1

This is likely the most suitable format for adjusting camera rotation in Three.js

camera.position.set( x_max*1.01, y_max*1.01, z_max*1.01 ).add(YourObject.position.clone());

If you modify the last line of your JavaScript code to adhere to the syntax provided above, it should function correctly:

 function searchCountry(lat,lng){

    var phi = (90 - lat) * Math.PI / 180;
    var theta = (180 - lng) * Math.PI / 180;

    camera.position.x = 200 * Math.sin(phi) * Math.cos(theta);
    camera.position.y = 200 * Math.cos(phi);
    camera.position.z = 200 * Math.sin(phi) * Math.sin(theta);
    camera.lookAt(mesh.position); // <<-- Adjust this line to match the format above!
  }

If you found this answer helpful, kindly mark it as Accepted Answer so others know you have resolved the issue. Thank you.

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

Streamlining the Process of Uploading Files using Selenium WebDriver

My current project involves automating the uploading of an HTML file. Unfortunately, the website I am working on has made this task more complicated than necessary. The code for the file upload section is as follows: <div class="form-row"> < ...

Switching between multiple images using Jquery on a click event

Hi there, I am currently working on a project where I need to use jQuery to switch between three images when clicked. Once the third image is clicked, it should cycle back to the first picture. I was wondering if there is a way to modify the code below so ...

Issue with error handling while using HTML5 geolocation in Chrome browser

I have a basic map that is supposed to load centered on the user's current location if they allow HTML5 geolocation. There is a fallback function in place for users who choose not to share their location, but it seems to be malfunctioning. Here is th ...

How can parameters be sent without using the .jshintrc file with the gulp-jshint package?

Currently in the process of transitioning a grunt project to a gulp project. In the existing gruntfile, there is a section for the jshint task that looks like this: jshint: { options: { trailing:true, evil:false, indent:4, ...

Stage setting timeout for the playwright

const test = defaultTest.extend({ audit: async ({ page }) => { await page.screenshot({ path: 'e2e/test.png' }); console.info('audit done!'); }, }); // ...more code test.only('audit', async ({ page, mount, audi ...

Error in identifying child element using class name

I need help accessing the element with the class "hs-input" within this structure: <div class = "hbspt-form".......> <form ....class="hs-form stacked"> <div class = "hs_firstname field hs-form-field"...> <div class = ...

The implementation of an onclick event in a freshly created HTML element is functioning solely on the final element

One issue I encountered was that when I generated page number buttons at the bottom of a page, the onclick event only worked with the last button created. Below is an example of how the page buttons were displayed: https://i.stack.imgur.com/wHwI0.png ...

Unexpected request detected by AngularJS $httpBackend

Attempting to setup a unit test for an AngularJS controller that utilizes a service making a $http.get call. Despite using $httpBackend.expectGET followed by $httpBackend.flush(), the application is attempting to make GET requests for template HTML resourc ...

Ensuring the stability and consistency of automatically generated serial numbers when sorting in ascending order in another column of the gridview

I am facing an issue with my list view on the page. There are three columns - serial number, row name, and row code. I have implemented sorting in ascending order for the row name using jQuery. However, when the sorting is applied, the serial numbers als ...

Running an Angular-made Chrome extension within an iframe: A guide

I'm currently working on creating a Chrome extension that displays its content in a sidebar rather than the default popup. I've come to realize that in order to achieve this, I need to use an iframe due to the limitations of the default chrome ex ...

JQuery Function for Repeatedly Looping through Div Elements

I've been experimenting with creating a loop that alternates the fade-in and fade-out effects for different elements. This is what I have so far: setInterval(function() { jQuery(".loop").each(function(index, k) { jQuery(this).delay(1200 ...

Creating a basic to-do app with PHP that utilizes AJAX to handle repetitive values

Whenever I try to add new items, I encounter a peculiar issue. Upon adding a new item, multiple values are generated. Even though I only input the first two values into the database via phpMyAdmin, clicking the button to display the new data causes a diffe ...

Ways to effectively link up Ajax/JavaScript with the back end

I have recently developed a PHP class that enables my users to easily manage their accounts by utilizing functions such as createAccount, updateAccount, and more. Typically, I create an 'interface' script for each function where I initiate the c ...

Retrieve information based on ID with AJAX in JSON format on ASP.NET

Here is a method from my web service: List<object[]> List1 = new List<object[]>(); [WebMethod(EnableSession = true)] [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.Respons ...

Is there a way to simulate the parameters injected into an fs callback without actually interacting with the filesystem during testing?

I'm currently utilizing Chai, Mocha, and Sinon for my testing framework. At the moment, I have a functioning test, but I find myself having to set up a directory and populate it with files just to make my tests run successfully. This approach doesn&a ...

Utilize a slider component to navigate a horizontal scrollView within a React Native application

I'm in the process of setting up a slider within a horizontal ScrollView to enhance page scrolling speed. I've successfully linked the page position to the slider value, so as I scroll the page, the slider thumb moves correspondingly. My setup i ...

Utilizing DOMStringMap data to populate CSS URLs

I am attempting to create a universal CSS modification for a webpage element that resembles: <button data-action="link" class="cardImageContainer coveredImage cardContent itemAction lazy lazy-image-fadein-fast" data-blurhash="lo ...

The webpage does not dynamically resize based on screen height

Encountered an issue with the excess space below the footer. Resolved it by implementing a jQuery sticky footer as CSS techniques were unsuccessful. However, facing a problem with the main content of the webpage. Adjustment of .bg-photo's height impa ...

Creating a custom shape in Three.js and applying a texture to it

After creating an irregular quadrilateral, I attempted to apply an image texture to it. However, I encountered an issue as I could successfully assign a color to the quadrilateral but not an image. What might be causing this error? var camera = new THRE ...

What is the best way to add a timeout to a $.ajax request and retry if it exceeds the set time limit?

Could someone provide me with a practical example of how to set a timeout for my $.ajax request and reattempt the request if it times out? I have gone through the documentation but still don't quite understand it. Any help would be greatly appreciated ...