【问题标题】:Cluster Markers with Google Maps API, locations from database使用 Google Maps API 的集群标记,来自数据库的位置
【发布时间】:2017-08-23 13:44:34
【问题描述】:

我正在创建一个谷歌地图,该地图根据我的数据库中的信息填充了标记。在这第一步中,我遵循了 Google 提供的tutorial

地图工作正常,但是由于我的一些标记靠得很近,我想利用标记聚类。我已经按照 Google 的 marker clustering 教程中的内容进行了操作。

但是,我找不到让它工作的方法。我的标记只是按原样显示,没有任何聚类。我想我已经完成了所有步骤,将 JS 文件链接到我的 HTML,下载标记图标和 JS 文件并将其上传到我的托管站点等。

如何继续从我的数据库中创建标记,同时对标记进行聚类?

我已经测试了谷歌标记聚类器教程中的确切代码,一切正常。 (但是标记不在我需要的位置。)

我的 HTML(PHP) 网页的简化版本如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>My Website</title>
    <style>
        map {
    height: 400px;
    width: 98%;
    border: 5px outset SteelBlue;
    }
    </style>
    </head>
<body>

                <!-- Google Map -->
                <div id='map'>
                </div>



<!-- Google MAPS API & Custom Maps JS-->

    <!-- This is my personal file that houses the main Javascript code -->
        <script src="findermap.js"></script>

    <!-- A link to download this file is provided by the Google tutorial -->
        <script src="markerclusterer.js"></script>

    <!-- Basic Google Maps API key link -->
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=MY-KEY-IS-USED-HERE&callback=initMap">
    </script>

</body>
</html>

这里基本上是我使用的 JavaScript 文件,“findermap.js”

            function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
              center: new google.maps.LatLng(0, 0),
              zoom: 1
            });


            var customIcons = {
                    type1: {
                      icon: 'icon_type1.png'
                    },
                    type2: {
                      icon: 'icon_type2.png'
                    },
                    type3: {
                      icon: 'icon_type3.png'
                    },
                    type4: {
                      icon: 'icon_type4.png'
                    }
            };
            var markers = [];
            var infoWindow = new google.maps.InfoWindow;


              // Change this depending on the name of your PHP or XML file
              downloadUrl('https://my-website.com/getinfo.php', function(data) {
                var xml = data.responseXML;
                var markers2 = xml.documentElement.getElementsByTagName('marker');
                Array.prototype.forEach.call(markers2, function(markerElem) {
                  var name = markerElem.getAttribute('name');

                  var address = markerElem.getAttribute('address');
                  var type = markerElem.getAttribute('type');
                  var point = new google.maps.LatLng(
                      parseFloat(markerElem.getAttribute('lat')),
                      parseFloat(markerElem.getAttribute('lng')));

                  var infowincontent = document.createElement('div');
                  var strong = document.createElement('strong');
                  strong.textContent = name
                  infowincontent.appendChild(strong);
                  infowincontent.appendChild(document.createElement('br'));

                  var text = document.createElement('text');
                  text.textContent = address
                  infowincontent.appendChild(text);
                  var icon = customIcons[type] || {};
                  var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: icon.icon,
                    label: icon.label
                  });


                  marker.addListener('click', function() {
                    infoWindow.setContent(infowincontent);
                    infoWindow.open(map, marker);
                  });


                 markers.push(marker);

                });

              });

                  var options = {
                      imagePath: '/clustericons/m'
                  };

              // Add a marker clusterer to manage the markers.
                  var markerCluster = new MarkerClusterer(map, markers, options);
            }

            function downloadUrl(url, callback) {
            var request = window.ActiveXObject ?
                new ActiveXObject('getinfo.php') :
                new XMLHttpRequest;

            request.onreadystatechange = function() {
              if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
              }
            };

            request.open('GET', url, true);
            request.send(null);
            }

            function doNothing() {}

【问题讨论】:

    标签: php mysql api google-maps google-maps-markers


    【解决方案1】:

    我找到了!这是解决方案。这是更新的 javascript 文件:

        var customIcons = {
                    type1: {
                      icon: 'icon_type1.png'
                    },
                    type2: {
                      icon: 'icon_type2.png'
                    },
                    type3: {
                      icon: 'icon_type3.png'
                    },
                    type4: {
                      icon: 'icon_type4.png'
                    }
            };
    
            function initMap() {
              var cluster = [];
              var map = new google.maps.Map(document.getElementById("map"), {
                center: new google.maps.LatLng(0, 0),
                zoom: 1,
                mapTypeId: 'roadmap'
              });
        var infowindow = new google.maps.InfoWindow();
    
              // Change this depending on the name of your PHP file
              downloadUrl('https://my-website.com/the-sweet-sweet-xml-info.php', function(data) {
                var xml = data.responseXML;
                var markers = xml.documentElement.getElementsByTagName("marker");
                for (var i = 0; i < markers.length; i++) {
                  var name = markers[i].getAttribute("name");
                  var address = markers[i].getAttribute("address");
                  var type = markers[i].getAttribute("type");
                  var point = new google.maps.LatLng(
                      parseFloat(markers[i].getAttribute("lat")),
                      parseFloat(markers[i].getAttribute("lng")));
    
                  var html= "<b>" + 
                  markers[i].getAttribute("name") + 
                  "</b> <br/>" + 
                  markers[i].getAttribute("address");
    
                  var icon = customIcons[type] || {};
                  var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: icon.icon,
                  });
                  google.maps.event.addListener(marker, 'click', (function(marker, i) {
                                return function() {
                                    infowindow.setContent(
                                    "<b>" + 
                                    markers[i].getAttribute("name") + 
                                    "</b> <br/>" + 
                                    markers[i].getAttribute("address")
                                    );
                                    infowindow.open(map, marker);
    
                                    //This sends information from the clicked icon back to the serverside code
                                    document.getElementById("setlatlng").innerHTML = markers[i].getAttribute("name");
                                }
                            })(marker, i));
                  cluster.push(marker);
                }
    
                var options = {
                      imagePath: '/location-of-cluster-icons/m'
                  };
    
                var mc = new MarkerClusterer(map,cluster,options);
              });
            }
    
            function bindInfoWindow(marker, map, infoWindow, html) {
              google.maps.event.addListener(marker, 'click', function() {
                infoWindow.setContent(html);
                infoWindow.open(map, marker);
    
              });
            }
    
            function downloadUrl(url, callback) {
              var request = window.ActiveXObject ?
                  new ActiveXObject('the-sweet-sweet-xml-info.php') :
                  new XMLHttpRequest;
    
              request.onreadystatechange = function() {
                if (request.readyState == 4) {
                  request.onreadystatechange = doNothing;
                  callback(request, request.status);
                }
              };
    
              request.open('GET', url, true);
              request.send(null);
            }
    
            function doNothing() {}
    

    【讨论】:

      【解决方案2】:

      谢谢你的回答,真的很有帮助。 我还想添加另一个功能,即标记聚类计算器。我也在另一页上找到它。所以基本上它有助于使聚类颜色更加均匀,因为你们存储在数据库中的数据总量。

      脚本的简化版本如下:

      <script>
          var customIcons = {
                          type1: {
                            icon: 'icon_type1.png'
                          },
                          type2: {
                            icon: 'icon_type2.png'
                          },
                          type3: {
                            icon: 'icon_type3.png'
                          },
                          type4: {
                            icon: 'icon_type4.png'
                          }
                  };
      
                  function initMap() {
                    var cluster = [];
                    var map = new google.maps.Map(document.getElementById("map"), {
                      center: new google.maps.LatLng(-7.952361, 110.619003),
                      zoom: 10,
                      mapTypeId: 'roadmap'
                    });
              var infowindow = new google.maps.InfoWindow();
      
                    // Change this depending on the name of your PHP file
                    downloadUrl('http://localhost/try/dashboard/examples/xml.php', function(data) {
                      var xml = data.responseXML;
                      var markers = xml.documentElement.getElementsByTagName("marker");
                      for (var i = 0; i < markers.length; i++) {
                        var name = markers[i].getAttribute("name");
                        var address = markers[i].getAttribute("address");
                        var type = markers[i].getAttribute("type");
                        var point = new google.maps.LatLng(
                            parseFloat(markers[i].getAttribute("lat")),
                            parseFloat(markers[i].getAttribute("lng")));
      
                        var html= "<b>" + 
                        markers[i].getAttribute("name") + 
                        "</b> <br/>" + 
                        markers[i].getAttribute("address");
      
                        var icon = customIcons[type] || {};
                        var marker = new google.maps.Marker({
                          map: map,
                          position: point,
                          icon: icon.icon,
                        });
                        google.maps.event.addListener(marker, 'click', (function(marker, i) {
                                      return function() {
                                          infowindow.setContent(
                                          "<b>" + 
                                          markers[i].getAttribute("name") + 
                                          "</b> <br/>" + 
                                          markers[i].getAttribute("address")
                                          );
                                          infowindow.open(map, marker);
      
                                          //This sends information from the clicked icon back to the serverside code
                                          document.getElementById("setlatlng").innerHTML = markers[i].getAttribute("name");
                                      }
                                  })(marker, i));
                        cluster.push(marker);
                      }
      
                      var options = {
                            imagePath: '/location-of-cluster-icons/m'
                        };
                      var markerCluster = new MarkerClusterer(map, cluster,
                      {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
      
             // For Cluster Calculator
                      markerCluster.setCalculator(function(markers, numStyles){
                          //create an index for icon styles
                          var index = 0,
                          //Count the total number of markers in this cluster
                              count = markers.length,
                          //Set total to loop through (starts at total number)
                              total = count;
      
                          /**
                           * While we still have markers, divide by a set number and
                           * increase the index. Cluster moves up to a new style.
                           *
                           * The bigger the index, the more markers the cluster contains,
                           * so the bigger the cluster.
                           */
                          while (total !== 0) {
                              //Create a new total by dividing by a set number
                              total = parseInt(total / 5, 10);
                              //Increase the index and move up to the next style
                              index++;
                          }
      
                          /**
                           * Make sure we always return a valid index. E.g. If we only have
                           * 5 styles, but the index is 8, this will make sure we return
                           * 5. Returning an index of 8 wouldn't have a marker style.
                           */
                          index = Math.min(index, numStyles);
      
                          //Tell MarkerCluster this clusters details (and how to style it)
                          return {
                              text: count,
                              index: index
                          };
                      });
      
                // END OF CLUSTER CALCULATOR
      
                    });
                  }
      
                  function bindInfoWindow(marker, map, infoWindow, html) {
                    google.maps.event.addListener(marker, 'click', function() {
                      infoWindow.setContent(html);
                      infoWindow.open(map, marker);
      
                    });
                  }
      
                  function downloadUrl(url, callback) {
                    var request = window.ActiveXObject ?
                        new ActiveXObject('the-sweet-sweet-xml-info.php') :
                        new XMLHttpRequest;
      
                    request.onreadystatechange = function() {
                      if (request.readyState == 4) {
                        request.onreadystatechange = doNothing;
                        callback(request, request.status);
                      }
                    };
      
                    request.open('GET', url, true);
                    request.send(null);
                  }
      
                  function doNothing() {}
              </script>

      【讨论】:

      • 这不是询问更多细节的正确方法。对此发表评论。
      猜你喜欢
      • 2021-03-21
      • 2021-02-08
      • 2018-05-20
      • 1970-01-01
      • 2017-03-11
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多