gmaps4rails zoom on one marker

2019-07-23 14:34发布

问题:

I'm using gmaps4rails, and I'd like to keep using the auto zoom feature, but in case I only have one marker I'd like to change the zoom, cause the default one is the maximum zoom.

Having read the related question I added this code to my javascript file:

$(function() {

//to address the problem with the zoom being set to maximum when there's only one marker
  Gmaps.map.callback = function() {
    console.log("in callback");
    if (Gmaps.map.markers.length == 1) {
     console.log("only one marker");
     //only one marker, choose the zoom level you expect
     Gmaps.map.map.setZoom(12);
    }
    else{
     //more than one marker, let's auto_zoom
     console.log("more markers");
     Gmaps.map.map_options.auto_zoom = true;
     Gmaps.map.adjustMapToBounds();
    }
  }
});

And when I read the console output (Safari's Web Inspector), I get both "in callback" and "only one marker", but the map doesn't get zoomed. On the other hand, when I type Gmaps.map.map.setZoom(12) into the console manually, it zooms out..

Is there maybe some other callback that gets called after this one? Or should I put this code somewhere else?