3

I have:

const map = L.map("mapid", {preferCanvas: true});
//....    
const circle = L.circle([47.6652642, -122.3161248], {
    color: '#ea647f',
    fillOpacity: 0.4,
    radius: 30
}).addTo(map);

but calling getBounds() on circle fails:

const bounds = circle.getBounds();

It fails inside function getBounds in Circle.js which is Leaflet code,
The Leaflet getBounds method code is:

getBounds: function () {
        var half = [this._radius, this._radiusY || this._radius];

        return new LatLngBounds(
            this._map.layerPointToLatLng(this._point.subtract(half)),
            this._map.layerPointToLatLng(this._point.add(half)));
    }

Trying to access this._map.layerPointToLatLng fails
I get the error that this._map is undefined
Any ideas?

===================================================

Please Note:
I also have a polygon defined, and calling the getBounds() on the polygon passes fine and works correctly, shows correctly on the map.
=> It is only the Circle.getBounds() that fails

Danielle
  • 3,324
  • 2
  • 18
  • 31

2 Answers2

2

Add center and zoom to the map.

const map = L.map("map", {center:[47.6652642, -122.3161248], zoom: 16 ,preferCanvas: true});
Falke Design
  • 10,635
  • 3
  • 15
  • 30
  • 1
    Thanks, that helped, but - FYI - I used `center:[0,0]` and `zoom: 1` because it doesn't really matter, because after I gather all the data that needs to be shown I call `map.fitBounds()` and it overrides those initial values!! Don't know to explain this, but at least initializing `L.map` as you suggest makes the `Circle.getBounds()` method pass... – Danielle Jan 05 '21 at 15:12
  • Maybe I can save someone a couple of minutes: circle.getBounds() only works if the circle was already added to a map. My hacky solution so far `circle.addTo(map); markersBounds.extend(circle.getBounds()); circle.removeFrom(map);` – BergListe Dec 06 '22 at 12:32
0

You need to initialise the map state with setView() or some other mechanism. The layerPointToLatLng calls will fail otherwise.

peeebeee
  • 2,541
  • 6
  • 21
  • 26