GMaps API V3 - Multiple Markers & InfoWindow

大兔子大兔子 提交于 2019-11-29 15:17:20

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.

brazorf

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.

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!