MapBox map.flyTo does not center

Viewed 550

I have a MapBox instance with a point on it. When I click the point, I want to zoom to the coordinate defined (in this case -158.2413336392218, 21.562096692790377):

  map.on('load', function () {
     map.addSource('places', {
        'type': 'geojson',
        'data': {
        'type': 'FeatureCollection',
        'features': [
     {
     'type': 'Feature',
     'properties': {
     'description':
     '<strong>HTS</strong>'
     },
     'geometry': {
     'type': 'Point',
     'coordinates': [-158.2413336392218, 21.562096692790377]
     }
  },

The issue is, when I click the point, it takes me close to, but not exactly center on those coordinates. A mile or so off. Intestingly, if I let it zoom to the point (~1 mile off), and then click the point again, I'm perfectly centered on the original point.

See the flyTo below:

  map.on('click', 'places', function (e) {
     alert(e.features[0].geometry.coordinates);
     map.flyTo({
        center: e.features[0].geometry.coordinates,
        zoom: 15,
        speed: 5, 
     });
  });

From that alert statement I put in, the first alert gives me "-158.2470703125,21.555284406923178", but the second alert (already zoomed in from the first click) gives me "-158.24133306741714,21.56209706697237". I have no idea how this is happening. I tried shortening the degrees to less than 10 decimal places, but that did nothing. I have no idea where the first coords are coming from. It doesn't seem to be rounding, but I don't what else it could be. Please help!

1 Answers

It seems that at low zoom levels (1.6 in this case), the coordinates get rounded. As you zoom further (2, 6, ..., 14) the coordinates don't get rounded and they're more accurate. I currently have two solutions 1) Start your map zoom at a larger zoom lever so your coordinates are more accurate 2) Zoom to the rounded/seemingly random coordinates, and then zoom again on 'moveend'. It's not really clean, but it'll work until we can get a better solution.

 map.on('click', 'places', function (e) {
   map.flyTo({
     center: e.features[0].geometry.coordinates,
     zoom: 14,
     speed: 5, 
   });

map.once('moveend', 'places', function (e) {
 map.flyTo({
   center: e.features[0].geometry.coordinates,
   zoom: 16,
   speed: 5,
 });
});
Related