Search code examples
javascriptasp.nethtmlgoogle-mapsgoogle-maps-api-3

MarkerClusterer not clustering markers


My map is pretty sluggish due to the large amount of data/markers stored in locations so I tried to get markerclusterer working shown here. Locations is just a c# string array that has a name, latitude, and longitude for each marker. For some reason the map still works but just shows individual markers and does not cluster them and I cannot figure out why. Any help would be appreciated.

<script type="text/javascript">

    var locations = [<%=locations%>];

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(30.2979536, -97.7470835),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var markers = [];

    for (var i = 0; i < locations.length; i++) {
        var marker = new google.maps.Marker({position: new  google.maps.LatLng(locations[i][1], locations[i][2]), map: map });
        markers.push(marker);
    }

  var markerCluster = new MarkerClusterer(markers);
</script>

Solution

    • pass the map into the MarkerClusterer

        var markerCluster = new MarkerClusterer(map, markers);
      

    proof of concept fiddle

    screenshot of resulting map

    You might want to convert the latitude and longitude to floating point numbers from strings (with parseFloat()).

    working example with MarkerClusterer

    code snippet:

    var locations = [
      [0, 30.2979536, -97.7470835],
      [1, 30.29, -97.747],
      [2, 30.2979536, -97.7470835],
      [3, 30.2979536, -97.7470835]
    ];
    
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(30.2979536, -97.7470835),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    
    var markers = [];
    
    for (var i = 0; i < locations.length; i++) {
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });
      markers.push(marker);
    }
    
    var markerCluster = new MarkerClusterer(map,markers,{imagePath: 'https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library@07f15d84/markerclustererplus/images/m'}); // was 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
    html,
    body,
    #map {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <!-- was https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js -->
    <script src="https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library@07f15d84/markerclustererplus/src/markerclusterer.js"></script>
    <div id="map"></div>