MarkerCluster谷歌地图没有分组我的标记

时间:2014-11-22 15:20:57

标签: javascript google-maps google-maps-api-3 google-maps-markers markerclusterer

首先,我获得了JSON //工作

的电台位置

JSON结构:

[{"number":31705,"name":"31705 - CHAMPEAUX (BAGNOLET)","address":"RUE DES CHAMPEAUX (PRES DE LA GARE ROUTIERE) - 93170 BAGNOLET","position":{"lat":48.8645278209514,"lng":2.416170724425901},"banking":true,"bonus":true,"status":"OPEN","contrat _name":"Paris","bike_stands":50,"available_bike_stands":45,"available_bikes":5,"last_update":1416677110000}]

其次我想用MarkerCluster分组标记,但MarkerCluster在我的所有标记中 为什么不分组?

function initialize() {

  var mapOptions = {
    center: new google.maps.LatLng(48.859875, 2.342253),
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true
  };

  var infoWindow = new google.maps.InfoWindow();
  var mcOptions = {gridSize: 50, maxZoom: 15, minimumClusterSize:10}

  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  $.getJSON("https://api.jcdecaux.com/vls/v1/stations?contract=Paris&apiKey=d98a9b59f1d1999cf1ab909051cc63bd46c66a46", function (data) {
    $.each(data, function (key, data) {

      var markers = [];

      for (var i = 0, length = data.address.length; i < length; i++) {
        var myLatlng = new google.maps.LatLng(data.position.lat, data.position.lng);
        var marker = new google.maps.Marker({
          position: myLatlng
        });

        markers.push(marker);
      }

      var markerCluster = new MarkerClusterer(map, markers, mcOptions);

    });
  });
  google.maps.event.addDomListener(window, 'load', initialize);
}

1 个答案:

答案 0 :(得分:1)

您正在为每个标记创建一个新的MarkerClusterer(如果您缩进代码,则更容易看到)

  • 将MarkerCluster的创建移出$ .each。

也:

  • google.maps.event.addDomListener(window,'load',initialize);移出初始化函数
  • 删除data.address.length上的内部循环(除非您的数据需要,否则不会查看所有数据)
function initialize() {

  var mapOptions = {
    center: new google.maps.LatLng(48.859875, 2.342253),
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true
  };

  var infoWindow = new google.maps.InfoWindow();
  var mcOptions = {
    gridSize: 50,
    maxZoom: 15,
    minimumClusterSize: 10
  };

  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  $.getJSON("https://api.jcdecaux.com/vls/v1/stations?contract=Paris&apiKey=d98a9b59f1d1999cf1ab909051cc63bd46c66a46", function (data) {
    $.each(data, function (key, data) {
      var myLatlng = new google.maps.LatLng(data.position.lat, data.position.lng);
      var marker = new google.maps.Marker({
        position: myLatlng
      });
      markers.push(marker);
    });
    var markerCluster = new MarkerClusterer(map, markers, mcOptions);
  });
}
google.maps.event.addDomListener(window, 'load', initialize);

working fiddle(带有经过修改的数据子集)