简体   繁体   中英

google maps: open infowindow after map & marker load

I'm working with google maps api 3. It's a bit of annoyance, but how do I get infowindow.open after the marker and the map have loaded?

I've tried to add various listeners such as tilesloaded and idle and haven't had any joy.

In this working example you see the infowindow is loading before anything else: http://codepen.io/anon/pen/WvbexY

function initialize() {
    if (document.getElementById("maper")) {        
       var latlng = new google.maps.LatLng(52.370778, 4.899448);
       var mapOptions = {
         zoom: 11,
         center: latlng,
         scrollwheel: "",
         scaleControl: "",
         disableDefaultUI: "",
          mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var tinygmaps = new google.maps.Map(document.getElementById("maper"), mapOptions);
    var marker = new google.maps.Marker({
      map: tinygmaps,
      position: tinygmaps.getCenter()
    });

    var contentString = '<p>WHY ME FIRST?</p>';
    var infowindow = new google.maps.InfoWindow({
      content: contentString,
      position: latlng,
    });
    infowindow.open(tinygmaps, marker);
    //var openwindow = google.maps.event.addListener(tileListener, 'tilesloaded', open_infowindow); // Hummmm!
  }
}
google.maps.event.addDomListener(window, 'load', initialize);


function open_infowindow() {
  infowindow.open(tinygmaps, marker);
  google.maps.event.removeListener(tileListener);  
};

Edit: Changed the codepen to listen for tilesloaded before displaying the infowindow. The fork of your codepen with the tilesloaded listener is here: http://codepen.io/brenzy/pen/VLYwGN

Because SO needs some code:

google.maps.event.addListenerOnce(tinygmaps, 'tilesloaded', function() {
  // open the infowindow
});

On my machine, listening for both tilesloaded and idle appear to function the same. (Without either listener, the infowindow is displayed before the map.)

I am assuming that your version didn't work, because you missed the line

infowindow.open(tinygmaps, marker);

when you were refactoring, so the infowindow was being opened before the listener fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM