Google Maps V3 InfoWindow ignores latLng position

Robin Lucas picture Robin Lucas · Oct 29, 2013 · Viewed 13.5k times · Source

My map has no markers. In response to a click on the map, it pops up an infowindow with Lat/long shown in decimal to 5 dp and in Degrees minutes seconds. An open window is always closed prior to responding to a new click. The position is specified by position: latLng, but the infowindow is ALWAYS at the top left. I've spent days on this, and I feel I'm missing something. Code snippet below. Any ideas?

google.maps.event.addListener(map, 'click', function (event) {
    var lat = event.latLng.lat(),
        lng = event.latLng.lng(),
        latLng = event.latLng,
        strHtml;
    //
    // strHtml build code omitted but succesfully uses lat and lng to produce
    // e.g. Latitude : 51.72229 N (51° 43' 20'' N)
    //      Longitude : 1.45827 E (1° 27' 30'' E)
    //
    // If an infowindow is open, then close it
    if (openedInfoWindow != null) openedInfoWindow.close();
    // latLng monitored to check it is there before use in infowindow
    alert(latLng); // returns correct values which position then ignores!
    var infoWindow = new google.maps.InfoWindow({
        position: latLng, 
        content: strHtml,
        maxWidth: 420
    });
    // Open infoWindow
    infoWindow.open(map,this);
    // Remember the opened window
    openedInfoWindow = infoWindow;
    // Close it if X box clicked
    google.maps.event.addListener(infoWindow, 'closeclick', function() {
    openedInfoWindow = null; 
    });    
});

Answer

Bryan Weaver picture Bryan Weaver · Oct 29, 2013

You have several problems with this code. The second parameter of the infowindow's open method has to be an MVCObject in the Core API only the Marker class can be used as an anchor. You should not need to set the infowindow variable to null and create a new infowindow object each time. You only need a single infowindow and then change its content and position. This way there is only one infowindow shown at a time.

Here is a fiddle of a working example: http://jsfiddle.net/bryan_weaver/z3Cdg/

relevant code:

google.maps.event.addListener(map, 'click', function (evt) {
       var content = "<div class='infowindow'>";
       content += "Latitude: " + evt.latLng.lat() + "<br/>";
       content += "Longitude: " + evt.latLng.lng() + "</div>";
       HandleInfoWindow(evt.latLng, content);
});

function HandleInfoWindow(latLng, content) {
    infoWindow.setContent(content);
    infoWindow.setPosition(latLng);
    infoWindow.open(map);
}