17

I have a leaflet map whose size depends on the size of the browser window. I would like the zoom level to be dynamically chosen so that it is as zoomed in as possible while showing the entirety of the bounding box.

Right now, I just have the zoom level hardcoded and the center point based on an average of points.

map = new L.Map('map', {
  center: new L.LatLng(
    latitudeSum/locations.length,
    longitudeSum/locations.length
  )
  zoom: 9
})

Instead, I'd like to give it a bounding box (two islands) and have the zoom level chosen based on the size of the window.

Mike McKay
  • 451
  • 1
  • 3
  • 12

5 Answers5

33

You could simply use:

var group = new L.featureGroup([marker1, marker2, marker3]);

map.fitBounds(group.getBounds());
Farhat Abbas
  • 2,727
  • 1
  • 16
  • 14
  • 1
    Useful answer - that is a better way for centering and zooming - before I was just centering with a manual calculation. FitBounds was the answer I need, but I figured out you could simply pass into two coordinates to fitBounds and be done. – Mike McKay Nov 01 '13 at 13:20
  • 2
    Definitely use the next answer unless you already have markers created. – Andy Apr 06 '16 at 15:01
18

Using @Farhat's answer, I figured out that all I needed was to pass an array of arrays:

map.fitBounds([
  [-4.8587000, 39.8772333],
  [-6.4917667, 39.0945000]
])
Mike McKay
  • 451
  • 1
  • 3
  • 12
  • 1
    This is obviously missing a right square bracket near the end. Not sure why you reverted my edit. – Jan Kyu Peblik Jul 24 '18 at 20:12
  • 1
    You're right about the bracket - thanks. I'll fix that. Your edit also had an extra comma though. – Mike McKay Jul 25 '18 at 02:32
  • 4
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas Code actually tested with trailing comma, too. (Because life is too short to bother with lines that pointlessly significantly differ in format.) – Jan Kyu Peblik Jul 25 '18 at 03:54
0

map.fitBounds() also works great if you're working with Google Map Polylines:

<!-- required for Leaflet Polyline support -->
<script type="text/javascript" src="https://cdn.rawgit.com/jieter/Leaflet.encoded/68e78190/Polyline.encoded.js"
crossorigin=""></script>

// polylines require backslashes to be escaped (Jinja example)
let encodedRoute = '{{ activity.strava_data['map']['polyline']|replace("\\", "\\\\")|safe }}';
let coordinates = L.Polyline.fromEncoded(encodedRoute).getLatLngs();
let map = L.map('map').fitBounds(coordinates);
naaman
  • 111
0

This is how I made it thanks to @Mike McKay! ;)

Note that I've added a couple of extra to the coords as a inner Padding, so the markers aren't right in the side of the map. This way looks beautifuler.


const [ ...coordinates ] = locations.map(marker => [ marker.coordinates.latitude + 
0.055, marker.coordinates.longitude + 0.055 ])

map.fitBounds([ ...coordinates ])

VUE.JS WAY:

mounted () {
   this.$nextTick(() => {
        this.initialZoom()
   })
}


methods: {
   initialZoom () {
       const map = this.$refs.myMap.mapObject
       const [ ...coordinates ] = this.locations.map(marker => [                                  
                                          marker.coordinates.latitude + 0.055,
                                          marker.coordinates.longitude + 0.055 
                                   ]) 

map.fitBounds([ ...coordinates ])
Despertaweb
  • 101
  • 1
0

I want to thank these contributors. I just did this:

var mymap = L.map('mapid').setView([<?php echo "$alat, $alon" ?>],8);

mymap.fitBounds([ @@ echo "[$maxlat, $maxlon],[$minlat, $minlon]"; @@ ]);

... and it works like a charm. The @@ chars are the php brackets which stackexchange removes) Many thanks! I tried all kinds of computational schemes but did not know about fitBounds. I'll be ripping out a lot of superfluous code.

MrXsquared
  • 34,292
  • 21
  • 67
  • 117