The marker on the Three JS globe is constantly visible inside the globe or positioned far outside its boundaries

As a beginner in programming and React three fiber, I am struggling to understand why the marker I place on the globe using geolocation data won't stay attached. Despite my attempts to convert latitude and longitude to Cartesian coordinates, the marker still won't stick to the globe. The sphereGeometry is set to 1 in my equations since the radius has been omitted. Could it be a simple mistake that I am overlooking? Any help in identifying this issue would be greatly appreciated as I am currently stuck on this problem. Below is some sample code for reference.

function Sphere() {

  const globeRad = 1;
  const xpos = 30;
  const ypos = 30;

  function convertLatLongToCartesian(p){
    let lat = p.lat * (Math.PI/180);
    let lng = p.lng * (Math.PI/180)
  
    let x = Math.cos(lat) * Math.sin(lng)
    let y = Math.sin(lat) * Math.sin(lng) 
    let z = Math.cos(lat) 

    return {x,y,z}
  }

  let point1 = {
    lat: 38.9513216,
    lng: -104.7986176
  }

  let point2 = {
    lat: -23.6345,
    lng: 102.5528
  }

  let pos = convertLatLongToCartesian(point2)
  console.log(pos)

  const [colorMap, normalMap,specularMap, cloudsMap] = useLoader(TextureLoader, [greyEarth,normMap, specMap, clouds]);

  const earthRef = useRef();
  const cloudsRef = useRef();
  const coordRef = useRef();

  useFrame(({clock}) => {

    const elapsedTime = clock.getElapsedTime();
    earthRef.current.rotation.y = elapsedTime / 20;
    cloudsRef.current.rotation.y = elapsedTime / 15;
    coordRef.current.rotation.y = elapsedTime / 20;
  })
 
  return (
    <>
      <pointLight color="#f6f3ea" position={[2,0,5]} intensity={1.2}/>
      <Stars radius={300} depth={60} count={20000} factor={7} saturation={0} fade={true}/>
      <mesh ref={cloudsRef}>
        <sphereGeometry args={[1.005,30,30]}/>
        <meshPhongMaterial 
          map={cloudsMap} 
          opacity={0.4} 
          depthWrite={true} 
          transparent={true} 
          side={THREE.DoubleSide}
        />
      </mesh>
      <mesh ref={earthRef}>
        <sphereGeometry args={[1,30,30]}/>
        <meshPhongMaterial specularMap={specularMap}/>
        <meshStandardMaterial map={colorMap} normalMap={normalMap} metalness={0.4} roughness={0.7}/>
        <mesh ref={coordRef} position={pos.x,pos.z,pos.y}>
          <sphereBufferGeometry args={[0.1,20,20]}/>
          <meshBasicMaterial color="red"/>
        </mesh>
      </mesh>
    </>
  )
}

export default Sphere
Please provide me with any feedback on what might be causing the issue. Thank you!

Answer №1

Experiment with the following code:

let x = Math.sin(lat)* Math.sin(lng)
let y = Math.cos(lat) 
let z = Math.cos(lat) * Math.sin(lng)

This is necessary because of the axis orientation in three.js:

  • X theoretical -> Z three.js
  • Y theoretical -> X three.js
  • Z theoretical -> Y three.js

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

How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "d ...

What is the best way to stack col-xs-6 elements instead of having them side by side?

My form fields are currently set up using 3 col-xs-6 classes, but I'm not seeing the desired layout. I am aiming for: | col-xs-6 | | col-xs-6 | | col-xs-6 | However, what I am getting is: | col-xs-6 | col-xs-6 | | col-xs-6 | I understand that th ...

What is the best way to cycle through a JSON array of objects using JavaScript and jQuery?

Currently, my focus is on understanding JavaScript and JSON objects along with arrays. One of the tasks assigned to me involves iterating through the following array: {"6784": {"OD": [ { "od_id":"587641", ...

Learn how to effortlessly integrate and utilize a bpmn file in a Vue component by leveraging the raw-loader

As a newcomer to bpmn-js, I am facing the challenge of importing and utilizing a .bpmn file within a vue.js component (BPMNViewer.vue). Despite my efforts in researching, I could only find recommendations to use the raw-loader. Consequently, I am currently ...

How can you determine when a download using NodeJS HTTPS.get is complete?

Currently, I am facing an issue while downloading a file. My goal is to perform an action immediately after the download is complete. Specifically, I aim to import a .js file as soon as it finishes downloading. var request = https.get('https://m ...

Comparing a hexadecimal string from a buffer in JavaScript with Python

I am looking to output a hex escaped sequence string from a Buffer. For example: buffer = .... // => <Buffer d3 e9 52 18 4c e7 77 f7 d7> If I use the following: console.log(buffer.toString('hex')); The result is: d3e952184ce777f7d7 ...

Activating the Speech Recognition feature in a form triggers the submission of a post

Currently, I am integrating webkitspeechRecongition into a form to allow users to enter data using their voice by pressing a button. However, a challenge arises when the call is triggered by a button within the form as it results in a post/submit action th ...

A step-by-step guide on how to verify a selection using JavaScript

Is it possible to validate the select option with JavaScript? For example, if a user selects "Admin," then the page works for admin login. If they select "Vendor," then it works for vendor login. <table class="login_table" width="100%" border="0" cells ...

React - Struggling to modify state with setState within an onClick event

Having trouble updating the state with setState inside an onClick event on a button. I've added a console.log inside the function and it works, but the setState doesn't update the state. I've attempted two different approaches: <button o ...

Node.js module retriever showing as blank

My current challenge involves the creation of a settings class with one getter. Here is how it currently looks: class Configuration { get endpoint() { return 'https://api.example.com'; } } module.exports.Configuration = Configuration; In a ...

Implementing Content-Security-Policy for a web application embedded in an iframe

Hey there! I've got this cool webapp called myApp, developed using Spring Boot and Vaadin. It's going to be deployed on a Tomcat server at http://tomcatserver:8080/myApp Now, what I want to do is display the webapp in an iframe like this: <if ...

Deciphering the $resource factory along with the @ symbol prefix

Under this particular service: vdgServices.factory('UserService', ['$resource', function($resource) { return $resource('api/users/:id', {}, { doGet: { method: 'GET', params: { i ...

Working solely with CDNs, harness Vuetify alongside i18n for enhanced features

Currently, I am developing a Vue project within a static environment that lacks Node or Vue-cli support. In order to utilize Vue, Vuetify, and vue-i18n, we are incorporating them through CDNs. Our goal is to translate the Vuetify components using Vue-i18n ...

What are the steps to implement email validation, Saudi mobile number validation, and national ID validation in cshtml?

Looking to implement validations for the following fields: email, mobile number (must be 10 numbers and start with 05), and National ID (must be 10 numbers and start with 1 or 2) <input class="form-control" type="text" id="txt ...

Having difficulty setting custom icons for clustering in Google Maps MarkerClusterer due to the absence of position data

I am struggling to understand the documentation for this utility. It seems that to customize cluster icons, I need to convert the cluster icon to a marker using the MarkerClusterer's renderer property and then apply icon styles as if it were a normal ...

What methods work best for handling extensive arrays in Javascript language?

I am currently working on a React JS application that interacts with an API to fetch a JSON object containing a large array of over 10,000 objects. This array is then used to populate a table with the help of various filters and options available through c ...

What steps can I take to prevent Javascript/JQuery from repositioning other elements on the webpage?

Is there a way for the animation code to only affect the show/hide toggle buttons and not interfere with the other jQuery code I have implemented for hiding and showing div text? When I included the animate code in my js page, it caused issues with the exi ...

Is there an issue with invoking Spring controller methods from JavaScript (via ajax) that is causing them

Using JavaScript to send a request to a method in Spring controller, the code looks like this: <script language="javascript" type="text/javascript"> var xmlHttp function show() { if(typeof XMLHttpReques ...

Substitute a single occurrence of the dollar sign with an HTML tag

I have been attempting to insert an HTML tag into a price on my e-commerce website. Specifically, I am looking to add a tag between the "$" and the numerical value (e.g. $5.00), but I am unable to locate the core file where I can place the code between the ...

Attention: React is unable to identify the `pId` property on a DOM element

After removing the span tag below, I noticed that there were no warnings displayed. <span onClick={onCommentClick} className={'comment'}> <AiOutlineComment className={"i"} size={"20px"}/> Co ...