Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

996
Vistas
Mapbox GL JS: change zoom depending on search range

Maybe it is a stupid question but anyway,

On the search page in my application, I have a range input that determines search range (min 5 km, max 50 km.). Depending on set value, I'd like to change current zoom in MapBox GL map so that it displays only the area that has been set in this input (if search range is about 10 km., I should see only a map sector with a radius of 10 km.). I'm a bit weak at math, which prevents me to find this correlation.

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

So you want the map area to encompass a circle of a size specified in kilometres.

One simple (but slightly bloaty) way to do this would be using Turf.

const rangeCircle) = turf.circle(map.getCenter().toArray(), radius, { units: 'kilometers' });
map.fitBounds(turf.bbox(rangeCircle))

That way you don't need to explicitly compute the zoom level - Mapbox's fitBounds() will figure that out for you.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Finally I figured out how to do that using Turf.js. Here is my solution:

function fitToRadius(radius) {
  const { lng, lat } = mapbox.getCenter();
  const center = [lng, lat];
            
  const rangeCircle = turf.circle(
    center,
    radius,
    { units: "kilometers"}
  );

  const [coordinates] = rangeCircle.geometry.coordinates;

  const bounds = new mapboxgl.LngLatBounds(
    coordinates[0],
    coordinates[0]
  );

  /* Extend the 'LngLatBounds' 
    to include every coordinate in the bounds result. */
  coordinates.forEach((coord) => bounds.extend(coord));

  mapbox.fitBounds(bounds);
}

Thanks to Steve Bennett for his hint about Turf.js.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda