Set zoom level of a google map so that all markers are visible

Hi out there,
A couple of months ago I needed to set the zoom level of a Google Map so that all markers in the map are visible. After hours of reading the API documentation, I did not find any solution on that issue, so I wrote a little Javascript function that does exactly that.

This function has to be called after all markers have been inserted into the map.
Here I set up a quick example: http://www.adick.at/wp-content/uploads/map/

EDIT:
The above example is deprecated. It is based on a function I wrote some months ago –
now there is a better and more common way for doing this: http://econym.org.uk/gmap/example_map14.htm

Cheers
Alex

9 Gedanken zu „Set zoom level of a google map so that all markers are visible“

  1. Hi Mohan,
    thanks for this! Actually, the time I wrote this post I did some research on that issue again and I then found these „native“ Google-funtions for doing that. I simply wanted to post my own solution anyway, maybe I should mention the safer and more common way in the post! 😉

  2. Hi Aiska,
    it’s a pity that google’s functions do not work properly.

    Your formula for getting the zoom level looks very promising – does it work 100%?

  3. Hi Alex,

    Ahh… you’re right
    i miss to divide 57.2958 in each point when i calculating distance
    so the formula is not 100% work. especially in lower zoom.

    so i change the formula :

    var zoom = Math.floor(8 – Math.log(1.6446*dist / Math.sqrt(2 * (mapdisplay * mapdisplay))) / Math.log (2));

    i hope this formula work.

    Thank you for your advice.

  4. Hi Alex. Probably, the native way that you’ve found is similar with below, isn’t it? 🙂

    //server side returns marker information by JSON type
    function loadAllMarkers(url, target_map)
    {
    jQuery.ajax({
    url: url,
    type: „get“,
    dataType: „json“,
    success: function(markers) {
    var bound = new GLatLngBounds();
    markers.each(function(marker) {
    var latlng = new GLatLng(marker.latitude, marker.longitude);
    bound.extend(latlng);
    target_map.addOverlay(new GMarker(latlng, {title:marker.name}));
    });
    target_map.setCenter(bound.getCenter());
    target_map.setZoom(map.getBoundsZoomLevel(bound));
    }
    });
    }

  5. Hi,
    I am using the cluster marker to show the different plants of an organization across the world. My problem is in the database, there are some plants which have the same name, though with different IDs. So, when I click that cluster, the markers aren’t shown for that location. Could someone help me with this please? Thanks a ton.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.