Search code examples
javascriptgoogle-mapsmapsgeojson

Google Maps Api, GeoJson and InfoWindow


Can someone tell me why the InfoWindow doesn't appear at first click? After the first click it always works fine...

I'm just loading data from a geojson file and try to adding a click event.

There are some problems anchoring an infowindow to a MVCObject.

var anchor = new google.maps.MVCObject();
anchor.setValues({//position of the point
    position:event.latLng,
    anchorPoint:new google.maps.Point(0,-40)});

infoWindow.open(map, anchor);   

Here is the code: https://jsfiddle.net/ajcL2y9p/


Solution

  • I removed the var infoWindow from inside the click listener and it works fine.

    JSFiddle

    Like this:

        var infoWindow = new google.maps.InfoWindow({
            content: "",
            pixelOffset: new google.maps.Size(0, -30)
        });
        // When the user clicks, set 'isColorful', changing the color of the letters.
        map.data.addListener('click', function (event) {
    
            event.feature.setProperty('isColorful', true);
    
    
    
            infoWindow.setContent('<div>test</div>');
    
            var anchor = new google.maps.MVCObject();
            anchor.setValues({ //position of the point
                position: event.latLng,
                anchorPoint: new google.maps.Point(0, -40)
            });
    
            infoWindow.open(map, anchor);
    
        });
    

    infoWindow was only being initialized in the first click. If you place it outside you initialize it and then only set the content.