开发者

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); 
}


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜