GMaps API V3 - 多标记&信息窗口

时间:2011-07-28 21:36:01

标签: google-maps-api-3 google-maps-markers infowindow

我知道,这是经常性的但是...我的多个标记存在很大问题:它们都具有相同的标题和相同的infowindow内容。

我在很多网站上搜索过,但是我的代码中没有找到问题所在。 我希望你能帮助我(我确信是这样的!)

这是我的代码:

<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>

我真的希望有人可以告诉我我的错误,并感谢你们的帮助!


不,我真的不明白, 它应该是我在代码中看不到的东西:

<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>

感谢您的帮助!! :)

3 个答案:

答案 0 :(得分:5)

您必须存储所有标记和所有信息窗口的引用。这是主要的想法。这是我之前找到并使用过的链接

http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/ 这是众所周知的问题。有很多关于它的信息。尝试搜索there

我希望它会有所帮助。

答案 1 :(得分:1)

我也遇到了这个,我刚用完它(一个相当混蛋的东西,imho)。

这里的主要问题是异步geocoder.geocode()函数:你正在编写代码的内联回调正在任意时间执行(谷歌回答你的请求的时间),它没有任何内容做你的周期。

出于这个原因,您的 i 计数器变量通常会包含最后一个可能的值,因为执行短 循环比要求达到的http请求快得多服务器然后回来。

主要是,解决方案正在与此相结合

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

用这个

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

正如Ruslan Polutsygan指出的那样。 对我来说真正的诀窍是在地理编码器回调之外保留任何迭代操作。所以,这是'核心':

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);
  });
}

这就是我使用它的方式:

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

其中 data 是我在服务器端生成的json变量,它由名称和地址(我们传递给地理编码器的那个)组成。

显然,你必须在其他地方初始化你的地图(我在jquery document.ready()中做)并将它声明为全局变量,就像infoWindow实例一样。

答案 2 :(得分:0)

以下是适用于我的示例代码

<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>