webglearth / webglearth2

[UNMAINTAINED] WebGL Earth 2 - the source code of the project
Apache License 2.0
884 stars 212 forks source link

Lat/Lng data from touchstart event #129

Closed eprtha closed 2 months ago

eprtha commented 2 months ago

I'm struggling for quite long time to get the Lat/Lng data from touch events but not successful yet. If anyone knows how to do it, please share. Thanks in advance.

sebastian-marinescu commented 2 months ago

Check out their API-example: https://examples.webglearth.com/#apidemo

In the canvas-box, with the WebglEarth-demo in it, in the bottom right corner you see the coordinates on mouseover. If you scroll down, you see the source-code of that demo.

There you will find some answers, specifically this bit looks relevant for you:

        // Print coordinates of the mouse
        map.on('mousemove', function(e) {
          document.getElementById('coords').innerHTML = e.latlng.lat + ', ' + e.latlng.lng;
        });

Something similar is also used in another API-example.

I think this should give you a good idea 👍

eprtha commented 2 months ago

Thanks for the response. That function is for mouse event which contains lat/lng data. But touch event data seems no lat/lng data in it ;-(

sebastian-marinescu commented 2 months ago

Please for the future, it's best to provide a jsbin/codepen with a (not-)working example.

For now: I couldn't reproduce your issue, because it works for me.

WebGL Earth Touch Test: https://codepen.io/sebastian-marinescu/pen/NWZWowv

I am guessing you where adding the event-listener on document/body?

sebastian-marinescu commented 2 months ago

The important thing in the JS:

 var lastTouchedLatLng = undefined;

  earth.on('touchstart', function(e) {
    console.log('onTouchstart: ', e);
    if (e.latlng) {
      lastTouchedLatLng = e.latlng; 
    }
  });

  earth.on('touchmove', function(e) {
    console.log('onTouchmove: ', e);
    if (e.latlng) {
      lastTouchedLatLng = e.latlng; 
    }
  });

  earth.on('touchend', function(e) {
    console.log('onTouchend: ', e);
    if (lastTouchedLatLng) {
     console.info('Last Latitude/Longitude: ', lastTouchedLatLng); 
    }
  });

In touchend, there really aren't lat/lng-coordinates, but in touchstart and touchmove, there are. So we save the last touched coordinates in theses two events, and in the end in "touchend" we do something with it.

eprtha commented 2 months ago

I really appreciate your help. I found out the problem based on your advice :-) It was caused by using earth.addEventListener instead of earth.on. Thanks.

sebastian-marinescu commented 2 months ago

I'm glad it helped :)

Good luck with your project, and don't forget to close this issue 👍