【问题标题】:Google Maps Markerclusterer won't load from XMLGoogle Maps Markerclusterer 不会从 XML 加载
【发布时间】:2013-04-22 06:31:48
【问题描述】:

我想首先说我知道这个问题过去曾被问过,但我无法得到旧的答案。在过去的 7 个小时里,我一直在使用 Google Maps Markerclusterer。我对 Javascript 比较陌生,并且能够为我的在线目录构建 Google 地图。我找到了 Makerclusterer,并认为这将是我标记过多问题的完美解决方案。问题是,我只知道如何从 XML 中读取,而此示例代码从 JSON 中读取。在尝试了几个小时让它从 XML 中读取之后,我想我可以简单地将我的 XML 转换为 JSON 格式,这将是一个简单的修复,但这也不起作用。

这是我们都知道并且喜欢在我的服务器上运行良好的 MarkerClusterer 示例: (集群文件)

这是我动态生成的 XML 文件(它包含城市名称、经度和纬度坐标): (XML 文件)

以下是示例 MarkerClusterer 代码。我已经阅读了数十篇“只需将标记点放入数组并将其提供给集群器”的 cmets,但我现在已经失败了十几次。任何意见表示赞赏。

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/data.json">
</script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>

<script type="text/javascript">
  function initialize() {
    var center = new google.maps.LatLng(37.4419, -122.1419);

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var markers = [];
    for (var i = 0; i < 100; i++) {
      var dataPhoto = data.photos[i];
      var latLng = new google.maps.LatLng(dataPhoto.latitude,
          dataPhoto.longitude);
      var marker = new google.maps.Marker({
        position: latLng
      });
      markers.push(marker);
    }
    var markerCluster = new MarkerClusterer(map, markers);
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

【问题讨论】:

    标签: xml maps markerclusterer


    【解决方案1】:

    好吧,如果您必须使用 xml,好消息是它并没有那么困难。访问 xml 元素的工作方式与访问普通 DOM 非常相似,但有许多不同之处。

    需要注意的一点是来自 xml 的所有数据都是字符串,因此在需要 Number 的地方必须转换为 Number 类型。例如在创建 google.maps.LatLng 时处理 lat & lon 值等。至于加载要读取的 xml,我们将使用 ajax 来加载它。

    我整理了一个示例,其中包含一些额外的实用程序(注意用于选择不同状态的选择,以及可单击以显示信息窗口的标记)供您仔细阅读。我加入 jQuery 库只是为了简化 ajax 请求代码,尽管 jQuery 也可以用于代码中我没有花时间转换的其他内容。 我很好奇,xml中的'count_unverified'是什么? 好吧,享受吧!

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Google Maps MarkerClusterer</title>
    <style type="text/css">
    .map-infowindow {
        border:3px ridge blue;
        padding:6px;
    }
    </style>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript">
    
    function initialize(elementId, stateAbbr) {
        var callback = function (data, status, xhr) {
            //data will be the xml returned from the server
            if (status == 'success') {
                createMap(elementId, data);
            }
        };
        //using jQuery to fire off an ajax request to load the xml,
        //using our callback as the success function
        $.ajax(
            {
                url : 'http://historyads.com/xml_state.php',
                data : 'state='+ stateAbbr,
                dataType : 'xml',
                success : callback
            }
        );
    }
    
    function createMap(elementId, xml) {
        var i, xmlMarker, lat, lng, latLng,
            map = new google.maps.Map(
                document.getElementById(elementId),
                {
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                }
            ),
            infoWindow = new google.maps.InfoWindow({maxWidth:200}),
            xmlMarkers = xml.getElementsByTagName('marker'),
            markers = [],
            latlngs = [],
            bounds = new google.maps.LatLngBounds();
        //private function, for scope retention purposes
        function createMarker(latlng, name, count_unverified) {
            latlngs.push(latlng);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map
            });
            google.maps.event.addListener(
                marker,
                "click",
                function () {
                    var info = '<div class="map-infowindow"><h4 class="map-info-title">';
                    info += name +'</h4><p class="map-info-content">count_unverified: ';
                    info += count_unverified +'</p>';
                    infoWindow.setContent(info);
                    infoWindow.open(map, marker);
                }
            );
            markers.push(marker);
        }
        for (i = 0; i < xmlMarkers.length; i++) {
            xmlMarker = xmlMarkers[i];
            //lat & lng in the xml file are strings, convert to Number
            lat = Number(xmlMarker.getAttribute('lat'));
            lng = Number(xmlMarker.getAttribute('lng'));
            latLng = new google.maps.LatLng(lat, lng);
            createMarker(
                latLng,
                xmlMarker.getAttribute('name'),
                xmlMarker.getAttribute('count_unverified')
            );
        }
        markerCluster = new MarkerClusterer(map, markers);
        for (i = 0; i < latlngs.length; i++) {
            bounds.extend(latlngs[i]);
        }
        map.fitBounds(bounds);
        return map;
    }
    
    function buildStatesSelect() {
        var i,
            select = document.getElementById('stateSelect'),
            states = [
                'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL',
                'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME',
                'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH',
                'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI',
                'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'
            ],
            len = states.length;
        for (i = 0; i < len; i++) {
            addOption(select, new Option(states[i], states[i]));
        }
        select.onchange = function () {
            var opt = this.options[this.options.selectedIndex];
            if (opt.value != '') {
                initialize('map', opt.value);
            }
        };
    }
    
    function addOption(select, option) {
        try {
            select.add(option,null); //standard method
        } catch(er) {
            select.add(option); //IE only
        }
    }
    
    google.maps.event.addDomListener(
        window,
        'load',
        function () {
            initialize('map', 'FL');
            buildStatesSelect();
        }
    );
    
    </script>
    </head>
    <body>
    <div id="map" style="width:500px; height:500px;"></div>
    <select id="stateSelect">
    <option value="">Select State</option>
    </select>
    </body>
    </html>
    

    【讨论】:

    • 非常感谢,愚蠢的名字!这很完美。 count_unverified 只是给定城市的商店计数。
    猜你喜欢
    • 2013-06-21
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 2020-10-28
    • 2014-10-05
    • 2016-01-25
    • 2011-07-19
    • 1970-01-01
    相关资源
    最近更新 更多