Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

986
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!