Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

995
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda