How to get map coordinates from screen coordinates?

1463
2
04-19-2023 01:32 PM
MelissaGearman
New Contributor II

I am attempting to do something that I assumed would be quite easy but since I'm relatively new to JavaScript, I have to be missing something. I'm trying to get the map coordinates based on screen coordinates (on a click event). The code below gives logs the screen coordinates. Reading the documentation, I assumed using the .toMap() method would convert the screen coordinates to map coordinates. Any idea what I am missing or if I'm even on the right track?

 

const map = new Map({
        basemap: "gray-vector",
    });

const view = new MapView({
        map: map,
        zoom: 7,
        center: [-93, 46.5], // longitude, latitude
        container: "viewDiv",
    });
 
const viewState = new ViewState({
        view: view,
    })

document.addEventListener("click", onClickCoordinates);

function onClickCoordinates(event) {
        var outCoordinate = []
        const xCoord = event.clientX;
        const yCoord = event.clientY;
        const mapCoordinates = viewState.toMap(outCoordinate, xCoord, yCoord)
        console.log(mapCoordinates);
    };
 
Thanks!
0 Kudos
2 Replies
Sage_Wall
Esri Contributor

Hi @MelissaGearman ,

You were defiantly on the right track, but you need to add the event listener to the view instead of the document.  I wrote a quick codepen, I hope it helps.

https://codepen.io/sagewall/pen/NWORQpB

     require(["esri/Map", "esri/views/MapView"],
      (Map, MapView) => {
        const map = new Map({
          basemap: "dark-gray-vector",
        });
        const view = new MapView({
          container: "viewDiv",
          map: map,
          center: [-61.125537, 35.863534],
          zoom: 3,
        });
        view.when(() => {
          view.on("click", (event) => {
            view.hitTest(event).then((response) => {
              const mapPoint = view.toMap(response.screenPoint);
              console.log(mapPoint);
            })
          });
        })
      });

 

0 Kudos
Sage_Wall
Esri Contributor

Now that I've thought about it more I guess you could do it even simpler as the map point is already available on the click event you don't really need the hitTest...

require(["esri/Map", "esri/views/MapView"], (Map, MapView) => {
  const map = new Map({
    basemap: "topo-vector"
  });
  const view = new MapView({
    container: "viewDiv",
    map: map,
    center: [-105, 40],
    zoom: 6
  });
  view.when(() => {
    view.on("click", (event) => {
      console.log(event.mapPoint);
    });
  });
});

 

0 Kudos