Mapbox – Adding and Removing Radius Circle After Fitting Map

jqueryleafletmapboxmapbox-gl

I am trying to add a range slider to zoom in and out of a Mapbox map to a radius in miles. I have the map and the slider working and I can sort of zoom in and out of the map by getting the bounds of the circle after drawing it. It works but I can not remove the layer with the old circle (radius) so it keeps drawing lots!

Firstly and I'm doing this correctly to sort of show map within mile radius and secondly why cannot I remove the blue circle. Also, is there a way without removing it immediately after getting bounds without it showing on the map?

After setting up the map, I set a circle with a given point and radius in meters.

var newValue = 5; // That's the new value of the slider //
var meters = 1609.34; // Meters in a mile //
var dist = newValue*meters;

var circle = L.circle([52.462610, -1.588580], dist).addTo(map);

map.fitBounds(circle.getBounds()); // Fit map to the radius

I then use this when the slider has changed value like

var dist = newValue*meters;

var circle = new L.circle([52.462610, -1.588580], dist).addTo(map);

map.fitBounds(circle.getBounds());
map.removeLayer(circle);  // not removing

I have only included Leaflet in the refs because lots of Mapbox information refers to it.

Update: I have it working but cannot really be sure it's working correctly as it stops zooming out after a certain amount?

I am using

var circle = new L.circle([52.462610, -1.588580], dist);
map.addLayer(circle);

var setdist = circle.getBounds();
console.log(setdist);
map.fitBounds(circle.getBounds())  

  
map.removeLayer(circle); 

Best Answer

Instead of using L.circle to get bounds (where circle has actually to be drawn on the map), I would recommend using turf.js library for that.

You can first use turf.buffer method to get desired circle around point, and then turf.bbox method to get bounding box of circle.

Function to fit map to desired circle could then look something like this:

function fitToCircle(point, radius) {
  var buffered = turf.buffer(turf.point(center), radius, {units: 'meters'});
  var bbox = turf.bbox(buffered);
  map.fitBounds([[bbox[0], bbox[1]], [bbox[2], bbox[3]]]);
}

You would then fit map to circle with the call:

var center = [52.462610, -1.588580];

var newValue = 5; // That's the new value of the slider //
var meters = 1609.34; // Meters in a mile //
var dist = newValue * meters;

fitToCircle(center, dist);