GMaps API V3 - 多个标记和标记信息窗口

发布于 2024-11-26 15:44:18 字数 4964 浏览 0 评论 0 原文

我知道,这是一个经常出现的问题,但是...我的多个标记有一个大问题:所有标记都具有相同的标题和相同的信息窗口内容。

我查了很多网站,但没有发现我的代码问题出在哪里。 我希望你能够帮助我(我确信情况确实如此!)

这是我的代码:

<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":"[email protected]"},{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"SomeAddress2","phone1":"0","phone2":"0","email":"[email protected]"}]; 


                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":"[email protected]"},{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"SomeAddress2","phone1":"0","phone2":"0","email":"[email protected]"}]; 


                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>

感谢您的帮助! :)

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":"[email protected]"},{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"SomeAddress2","phone1":"0","phone2":"0","email":"[email protected]"}]; 


                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":"[email protected]"},{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"SomeAddress2","phone1":"0","phone2":"0","email":"[email protected]"}]; 


                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 !! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

随梦而飞# 2024-12-03 15:44:19

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

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

我希望这会有所帮助。

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.

友欢 2024-12-03 15:44:19

我也遇到过这个,但我刚刚用完了(恕我直言,这是一件非常混蛋的事情)。

这里的主要问题是异步 geocoder.geocode() 函数:您编写代码的内联回调在任意时间执行(谷歌回答您的请求所需的时间),并且它与您的代码无关。为循环。

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

主要解决方案是将

GMaps JS Geocode 组合在一起:通过异步地理编码功能使用/传递变量?

与此

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

正如 Ruslan 所指出的波鲁齐甘。
对我来说真正的窍门是将任何迭代操作保留在地理编码器回调之外。所以,这就是“核心”:

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 实例一样。

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.

愛放△進行李 2024-12-03 15:44:19

这是适合我的示例代码

<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(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/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>

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(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文