ygoe
ygoe

Reputation: 20354

Get coordinates of screen point on the map

I'm using a MapBox GL map in my web application. It has some interactivity features that I handle through pointermove events. When the user moves the pointer over the map (it might also be outside the map, which has different functionality) I can show a custom marker element (simple <div>, position is absolute to the document) over the map where the pointer currently is. When the drag operation is completed, I need to know the map coordinates under that point.

So what I need is a method to convert a screen or document position (X, Y) to the coordinates (Lat, Lng) on the map in its current view state.

All I found was the getCenter method that gives me the center of the map (not the pointer positition) or the project method that seems to do the exact opposite of what I need. There also seems to be the map's "mousemove" event or similar, which could give me the coordinates in the event data, but I'm not using that event, because the drag operation could have started outside the map. Seems I need the reverse operation of the project method. Is there any?

Upvotes: 0

Views: 748

Answers (1)

ygoe
ygoe

Reputation: 20354

After digging through the map's source code regarding the "mousemove" event, I found the Map.unproject method. It seems to be what I need. It wants x/y coordinates relative to the map element, not the document though. I just didn't find it and Google didn't know what I mean either. Maybe this answer teaches Google a bit more about possible search terms not mentioned elsewhere.

Upvotes: 2

Related Questions