InfoWindow doesn't want to close with Google Maps Api V3

i can't close the info window of the marker i'm dragging, any idea ? Thanks for your help

function mapClick(event) {

        createLocationMarker(event.latLng);

}
function createLocationMarker(location) {
    var clickedLocation = new google.maps.LatLng(location)
    var gMarker = new google.maps.Marker({position:location, map:gMap2, draggable: true});

    gMap2.setCenter(location);
    displayMarkerPosition(gMarker);

     google.maps.event.addListener(gMarker, "dragstart", closeMapInfoWindow );
     google.maps.event.addListener(gMarker, "dragend", function() { displayMarkerPosition(gMarker); });
}

function closeMapInfoWindow() {infowindow.close(); }

function displayMarkerPosition(gMarker) {
    var message = "my message";
    var infowindow = new google.maps.InfoWindow(
    {   content : message,
    });

    infowindow.open(gMap2,gMarker); 
}

Answers


Yes, you define infowindow in a private scope, but access it outside that scope. Add this to the beginning of your script:

var infowindow;

And remove 'var ' from your constructor line:

infowindow = new google.maps.InfoWindow(

The finished code (from your sample) would look like this.

A little more background

When you define a variable with var, it is tied to that scope. If you define it in a function, only that function and other functions defined in it can access the variable. The only other way to pass it around is as a parameter in a function.

Update I would do this to facilitate multiple infowindows. Notice I have reverted to the original var declaration to keep it scoped to that function. I then return the reference to the object to use it later:

function mapClick(event) {
    createLocationMarker(event.latLng);
}
function createLocationMarker(location) {
    var clickedLocation = new google.maps.LatLng(location)
    var gMarker = new google.maps.Marker({position:location, map:gMap2, draggable: true});

    gMap2.setCenter(location);
    // Store reference to info window
    var info = displayMarkerPosition(gMarker);

    google.maps.event.addListener(gMarker, "dragstart", function(){ info.close } );
    google.maps.event.addListener(gMarker, "dragend", function() { displayMarkerPosition(gMarker); });
}

function displayMarkerPosition(gMarker) {
    var message = "my message";
    var infowindow = new google.maps.InfoWindow(
      {   content : message }
    );

    infowindow.open(gMap2,gMarker); 
    return infowindow; // Return the reference to the infowindow
}

Need Your Help

Having space in the same line in html

html html5

I would like to have some space between the same line.. I know there are elements such as <br>, <p> and others. Instead of using these, I would like to add little space between the char...

Joining two tables to update results in third table using like

sql oracle join

I am trying to join two tables and update the results in the third table.