2

I need to set pointers to a map a) when the map is initialized and b) when the map is moved. To get the markers, I make a call to my API like this:

var bounds = map.getBounds();

and then take the bounds to get the correct markers.

The problem is, that when I put that API-call inside

google.maps.event.addListener(map, "bounds_changed", function(){})

it gets called way too often while dragging the map, but if I use

google.maps.event.addListener(map, "idle", function(){})

map.getBounds is null upon initializing.

edit: More code

$(document).ready(function(){    initialize(); });

function initialize() {    mapOptions = {
      zoom : 13,
      minZoom : minimumZoomLevel,
      scrollwheel : false,
      panControl : false    };    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

   google.maps.event.addListener(map, "idle", function() {
      myfunction();    }); });

function myfunction(){    var bounds = map.getBounds(); }

bounds is null!

Raphael Jeger
  • 5,024
  • 13
  • 48
  • 79

1 Answers1

0

I'm using this piece of code here: http://boascervejas.com.br and it works ok:

var mapgoogle = null;
//do some stuff
var mapOptions = //something here
mapgoogle = new google.maps.Map(document.getElementById("map"), mapOptions);

google.maps.event.addListener(mapgoogle, 'idle', function() {
   var bounds = mapgoogle.getBounds();
   console.log(bounds);
   //it's only called when the "end of the drag" is fired
});

EDIT: full working example with jsfiddle (http://jsfiddle.net/pjhk3Lm9/):

js:

var map = null;

function initialize(lat, lng) {
   var myLatlng = new google.maps.LatLng(lat,lng);
   var mapOptions = {
      mapTypeControl: false,
      streetViewControl: false,
      center: myLatlng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    google.maps.event.addListener(map, 'idle', function() {
        console.log(map.getBounds());  
    })
};


navigator.geolocation.getCurrentPosition(
    function(position) {
        initialize(position.coords.latitude, position.coords.longitude);
    },
    function(position) {
        initialize(-23.5354986,-46.6839113);
    }
);

//html and css
<div id="map-canvas"></div>
#map-canvas {
    width: 400px;
    height: 400px;
    border:1px solid #FF0000;
}
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71