3

I know, it is a recurrent but... I have a big problem with my multiple markers : all of them have the same title and the same infowindow content.

I've searched on many websites, but I didn't find where is the problem in my code. I hope you'll be able to help me (I am sure it is the case !)

This is my code :

<script type="text/javascript">
            var map;
            var geocoder;
            $(document).ready(function() {
                initializeMap();
            });


            function initializeMap() {

                var people = [{"userid":"47","lastname":"lastname1","firstname":"firstname1","address":"SomeAddress","phone1":"00000000000","phone2":"","email":"me@me.com"},{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"SomeAddress2","phone1":"0","phone2":"0","email":"me@me.com"}]; 


                var center = new google.maps.LatLng(40.667, -73.833); 

                var myOptions = {
                    zoom: 8,
                    center: center,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                geocoder = new google.maps.Geocoder();

                for (i = 0; i < people.length; i++) {
                    var p = people[i];



                    geocoder.geocode( { 'address': p["address"]}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            map.setCenter(results[0].geometry.location);
                            var marker = new google.maps.Marker({
                                map:map,
                                draggable:false,
                                animation: google.maps.Animation.DROP,
                                title:p["lastname"] + " " + p["firstname"],
                                position: results[0].geometry.location
                            });


                            var myWindowOptions = {
                                content:
                                    '<h3>'+p["lastname"] + " " + p["firstname"]+'</h3>'+
                                    '<p>'+p["address"]
                            };

                            var myInfoWindow = new google.maps.InfoWindow(myWindowOptions);

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

 </script>

I realy hope somebody can show me my mistake(s) and thanks a lot for help !!


No, I really don't understand, It should be something I didn't see in my code :

<script type="text/javascript">
            var map;
            var geocoder;
            $(document).ready(function() {
                initializeMap();
            });


            function initializeMap() {

                var people = [{"userid":"47","lastname":"lastname1","firstname":"firstname1","address":"SomeAddress","phone1":"00000000000","phone2":"","email":"me@me.com"},{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"SomeAddress2","phone1":"0","phone2":"0","email":"me@me.com"}]; 


                var center = new google.maps.LatLng(50.833, 25.000); 

                var myOptions = {
                    zoom: 8,
                    center: center,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                geocoder = new google.maps.Geocoder();



                var infowindow = new google.maps.InfoWindow();

                var marker, i;

                for (i = 0; i < people.length; i++) {  
                    alert(people[i]['address']);
                    geocoder.geocode( { 'address': people[i]["address"]}, function(results, status) {

                        marker = new google.maps.Marker({
                            position: results[0].geometry.location,
                            map: map
                        });

                        google.maps.event.addListener(marker, 'click', (function(marker, i) {
                            return function() {
                                infowindow.setContent('<h3>'+people[i]["lastname"] + " " + people[i]["firstname"]+'</h3>');
                                infowindow.open(map, marker);
                            }
                        })(marker, i));
                    });
                }

            }
</script>

Thanks for help !! :)

Kara
  • 6,115
  • 16
  • 50
  • 57
Gerfaut
  • 119
  • 1
  • 3
  • 13

3 Answers3

5

You have to store references to all your markers and all infowindows. It is the main idea. Here is one the links I've found and used before

http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/ It is well known problem. There are much info regarding it. Try to searh there.

I hope it will be helpfull.

Ruslan Polutsygan
  • 4,401
  • 2
  • 26
  • 37
1

I've hit this one too, and i just ran out of it (a quite bastard of a thing, imho).

The main problem here is with the asynchronous geocoder.geocode() function: the inline callback in which you are writing your code is being executed at arbitrary time (the time google takes to answer your request), and it has nothing to do with your for cycle.

For this reason, your i counter variable will often contain the last possible value, because the execution of a short for cycle is much faster than an http request to reach the server and come back.

Mainly, the solution is combining toghether this

GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?

with this

http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/

as pointed from Ruslan Polutsygan. What made the real trick to me was keep any iterative operation outside the geocoder callback. So, this is the 'core':

function geocodeSite(site) {
  geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': site.place + ', IT'}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      site.position = results[0].geometry.location;
      addMarker(site);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

function addMarker(site) {
  marker = new google.maps.Marker({
      map: map,
      position: site.position,
      animation: google.maps.Animation.DROP,
      title: site.name
  });
  google.maps.event.addListener(marker, 'click', function () {
    infoWindow.setContent(site.name);
    infoWindow.open(map, this);
  });
}

and this is how i use it:

<script type='text/javascript'>
  var data = <?php print $geodata?>;
  for (var i = 0; i < witaly_data.length; i++) {
    geocodeSite(data[i]);
  }
</script>

where data is a json variable i generated on server side, and it consists of a name and an address (the one we pass to the geocoder).

Obviously, you have to initialize your map elsewhere (i do in jquery document.ready()) and declare it as a global variable, like the infoWindow instance aswell.

Community
  • 1
  • 1
brazorf
  • 1,943
  • 2
  • 32
  • 52
0

Here is the sample code that works for me

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script>
    var branches = '@Model.SerializedBranchesMapInfos'; //Info from server

    function setMarker(map) {
        if (branches != null && branches.length > 0) {
            branches = branches.replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, "\"");
            var branchesList = JSON.parse(branches);

            for (var i = 0; i < branchesList.length; i++) {
                addMarker(map, branchesList[i]);
            }
        }
    }

    function addMarker(map, branch) {
        var infowindow = new google.maps.InfoWindow();
        var marker = new google.maps.Marker({
            position: {
                lat: branch.Latitude,
                lng: branch.Longitude
            },
            map: map,
            title: branch.branchCode
        });

        var contentString = '<div><strong>' + branch.BranchCode + '</strong><br>' +
                                branch.Description + '</div>';

        google.maps.event.addListener(marker, 'click', function () {
            if (contentString == infowindow.getContent()) {
                infowindow.close(map, this);
                infowindow.setContent('');
            }
            else {
                infowindow.setContent(contentString);
                infowindow.open(map, this);
            }
        });
    }

    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(3.872310, 108.160445), // Initiaize with Riau Islands coordinates
            zoom: 6
        };
        var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
        setMarker(map);
    }

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