使用Google Maps API群集标记,来自数据库的位置

时间:2017-03-29 21:09:44

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

我正在根据数据库中的信息创建一个使用标记填充的Google地图。我已按照Google提供的tutorial进行了第一步。

地图工作正常,但由于我的一些标记靠得很近,我想利用标记聚类。我已经按照marker clustering上的Google教程了解了我的能力。

然而,我无法找到让它发挥作用的方法。我的标记只是显示它们的方式,没有任何聚类。我想我已经遵循了所有步骤,将JS文件链接到我的HTML,下载并将标记图标和JS文件上传到我的托管网站等。

如何从数据库继续创建标记,还可以对标记进行聚类?

我已经测试了google marker clusterer教程中的确切代码,一切正常。 (但是标记不在我需要的位置。)

我的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() {}

2 个答案:

答案 0 :(得分:0)

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

node_modules

答案 1 :(得分:0)

谢谢您的回答,这确实很有帮助。 我也想添加另一个功能,即标记聚类计算器。我也在另一页上找到它。因此从根本上说,即使您存储在数据库中的数据总量,它也有助于使群集颜色更加丰富。

脚本的简化版本如下:

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