Search code examples
google-maps-api-3polygons

google maps api v3 cannot get info boxes to show on dynamically created polygons


okay here is what i have . I'm using smarty to populate the coordinates, pulled from mysql, My little application draws over 300 polygons onto the uk map for county boundaries. I've manages to do that just fine and also colour them as i want. Now i have a problem i cant get any info boxes to show up.

A little more info, The reason for counties_zone is that some area have islands which break the polygon making a mess. so I've had to zone them to close the polygons properly.

the rest of my smarty variables should be pretty self explanatory.

<script>
var map;
var infoWindow;

function initialize() {
    var mapOptions={
        zoom: 6,
        center: new google.maps.LatLng(54.049976288319, - 2.8110410026615),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };

    var map=new google.maps.Map(document.getElementById('googleMap'),
            mapOptions);

    var counties={
    };
{foreach $counties as $county => $area}
    {foreach $area as $zone => $coords}
    counties["{$county}_{$zone}"]=new google.maps.Polygon({
        paths: [
        {foreach $coords as $coord}
                new google.maps.LatLng({$coord.0}, {$coord.1}),
        {/foreach}
        ],
        strokeColor: "#0000ff",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#{$coord.2}",
        fillOpacity: 0.6
    });
    counties["{$county}_{$zone}"].setMap(map);

    infowindow = new google.maps.InfoWindow();
    google.maps.event.addListener(counties["{$county}_{$zone}"], 'click', showInfoCounty);

    {/foreach}
{/foreach}

}

function showInfoCounty(event) {
    var contentString="<b>County</b><br />";
    contentString+="County name";

    // thhis works.
    console.log(contentString);

    // this works
    this.setOptions({ fillColor: "#000000" });

    // this doesnt work.

    // Replace our Info Window's content and position
    infowindow.setContent(contentString);
    infowindow.setPosition(event.latLng);
    infowindow.open(map);
}


google.maps.event.addDomListener(window, 'load', initialize);
</script>

Solution

  • The map variable is undefined in the showInfoCounty routine. Make it global (it is currently local to the initialize function, or at least the version of it you initialize is, there is a global one, but it isn't initialized).

    Minimal, Complete, Tested and Readable example showing issue: fiddle

    Change:

    var map=new google.maps.Map(document.getElementById('googleMap'),
            mapOptions);
    

    To:

    map=new google.maps.Map(document.getElementById('googleMap'),
            mapOptions);
    

    working fiddle