Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert coordinates to pixels on screen (and back again)

This is what I'm doing: Clicking a marker on the map to open a side panel and center the map on the marker. The side panel takes up 3/4 of the right side of the screen.

This is what I need to happen: Center the marker according to the 1/4 of the viewport that is left after the panel opens.

I can get the pixel coordinates of the marker and do the calculations of where it needs to translate to while the panel is animating open. The problem is that flyTo() only accepts LngLatLike objects and I cannot convert my pixel coordinates to latitude and longitude. Leaflet.js has a function called containerPointToLatLng() that came in handy before I switched to Mapbox GL.

Given the sofistication of Mapbox GL, despite its newness, I can only imagine this is a possibility. But how?

like image 285
Tomelower Avatar asked Dec 14 '16 01:12

Tomelower


2 Answers

The project and unproject methods make a lot of logic like this possible. If you have a click at a certain lngLat, and you want to position the map such that that geographic position is centered horizontally and at the 1/8 mark, you could:

  1. Take the geographic position and turn it into a pixel position with project
  2. Shift that pixel position right by (1/2-1/8) = 4/8-1/8 = 3/8 = 0.375 * map._containerDimensions()[0], by adding that number to it
  3. Turn that shifted pixel position back into a geographic position with unproject

Or, you might also be able to do it the easy way by using the offset option in your flyTo call.

like image 51
tmcw Avatar answered Sep 17 '22 20:09

tmcw


Even if it's an old question, to all those (like me) with the same requirement, I found an official example in mapbox site

like image 45
lbrutti Avatar answered Sep 18 '22 20:09

lbrutti