1

as part of my last.fm/google maps event mashup, I have to plot markers dynamically from last.fm API onto the google map.

This is all well but when I click the marker, only the last infowindow (for one gig) is displayed. I know the reasoning for this but struggle to implement it.

Currently I'm running a PHP loop through all the dynamic gig's locations (co-ordinates) and then passing this to the javascript. This makes more sense to me - and my knowledge of PHP is much better than JS:

<?php 

            foreach ($gigs->events->event as $js_event) { 

            $lat = $js_event->venue->location->children("geo",true)->point->children("geo",true)->lat;
            $long = $js_event->venue->location->children("geo",true)->point->children("geo",true)->long;
            $coords = "$lat,$long"; 

            ?>      

            var image = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=G|00CC99|000000',
            new google.maps.Size(40, 32),
            // The origin for this image is 0,0.
            new google.maps.Point(0,0),
            // The anchor for this image is the base of the flagpole at 0,32.
            new google.maps.Point(0, 32));

                    var marker = new google.maps.Marker({

                      position: new google.maps.LatLng(<?php echo $coords ?>),
                      map: map,
                      icon:image, 
                      title: '<?php echo str_replace('\'','',$js_event->title) ." at ". str_replace('\'','',$js_event->venue->name) ?>'

                    });

                    var contentString = '<?php echo str_replace('\'','',$js_event->title) ." at ". str_replace('\'','',$js_event->venue->name)?>'

                    var infowindow = new google.maps.InfoWindow({
                        content: contentString
                    });

                    google.maps.event.addListener(marker, 'click', function() {
                      infowindow.open(map,marker);
                    });

                <? } ?>

How could I add closure without fully refactoring the loops to JS and not PHP, etc. Unless this is one of the only solutions?

Many, many thanks.

cee
  • 39
  • 1
  • 4

1 Answers1

1

An easy way to isolate the scope of your marker variable is to wrap the invocation in an anonymous function:

var map = ...

(function() {
    var image = ...
    var marker = ...
    ...
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
    });
})();

As described here, the anonymous function will see anything in scope where it was declared. So inside the function can see map, which was in scope when it was declared. But outside the function, marker is invisible, so repeated clones of the anonymous function won't impact each other.

Community
  • 1
  • 1
user85461
  • 5,662
  • 1
  • 29
  • 38