将 MarkerClustererPlus 添加到现有 Google 地图 API 嵌入代码

Adding MarkerClustererPlus to existing Google Maps API embedded code

我希望将集群添加到我在 webflow 网站上嵌入的 google 地图 API。有谁能解释我将如何实现这个 ( https://codelabs.developers.google.com/codelabs/maps-platform-101-js#5 )。当它声明 'Import the marketcluster' 是嵌入时,我不确定在第一步中该怎么做。这个解决方案甚至可能吗?

这是当前设置...https://jsfiddle.net/geocodezip/nz14hubc/1/

// Variables for Google maps
var map, mapElem, markerImg, infoWindow, marker;
var markers = [], infoWindows = [], 
races = [{lat: 40.7127753, lng: -74.0059728, url:""},
{lat: 40.735657, lng:-74.1723667, url:""}];
var mapOptions = {
  mapTypeId: 'roadmap',
  //zoom: 13,
  //scrollwheel: false,
  styles: [
{
    "featureType": "administrative",
    "elementType": "labels.text.fill",
    "stylers": [
        {
            "color": "#444444"
        }
    ]
},
{
    "featureType": "landscape",
    "elementType": "all",
    "stylers": [
        {
            "color": "#f2f2f2"
        }
    ]
},
{
    "featureType": "poi",
    "elementType": "all",
    "stylers": [
        {
            "visibility": "off"
        }
    ]
},
{
    "featureType": "road",
    "elementType": "all",
    "stylers": [
        {
            "saturation": -100
        },
        {
            "lightness": 45
        }
    ]
},
{
    "featureType": "road.highway",
    "elementType": "all",
    "stylers": [
        {
            "visibility": "simplified"
        }
    ]
},
{
    "featureType": "road.arterial",
    "elementType": "labels.icon",
    "stylers": [
        {
            "visibility": "off"
        }
    ]
},
{
    "featureType": "transit",
    "elementType": "all",
    "stylers": [
        {
            "visibility": "off"
        }
    ]
},
{
    "featureType": "water",
    "elementType": "all",
    "stylers": [
        {
            "color": "#2bb0e6"
        },
        {
            "visibility": "on"
        }
    ]
}
]
  
};

function initialize() {
  markerImg = {
    url:'https://uploads-ssl.webflow.com/5f58a4616a9e71d63ca059c8/5fa18680b95c219254ad0c9c_place-marker.png',
    size: new google.maps.Size(46, 57),
    anchor: new google.maps.Point(23, 54),
  }
                  
  // Display a map on the page
  mapElem = document.getElementById('map_canvas');
  map = new google.maps.Map(mapElem, mapOptions);
  map.setTilt(45);
  
  

  // Loop through our array of races
  for(i = 0; i < races.length; i++) {
    var race = races[i];
  
    // Generate an infowindow content for the marker
    var infoWindow = new google.maps.InfoWindow();
    infoWindow.setContent(
      '<div class="bg-race"</div>' +
      '<p>'+race.name+'<br>Next race: '+race.date+'</p>' +
      '<a href="'+race.url+'" target="_new"> Race wesbsite </a>'
    );
    infoWindows.push(infoWindow);
  
    // Place a marker on the map
    createMarker(race.lat, race.lng, i);
  }
  
  // Center the map fitting all markers on the screen
  fitToMarkers();
}

function createMarker(x, y, i) {
  marker = new google.maps.Marker({
    map: map,
    icon: markerImg,
    position: new google.maps.LatLng(x,y),
    title: races[i].name
  });
  marker._index = i;
  markers.push(marker);
  
  // Click event on marker
  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      // Close last opened infowindow if any
      if(infoWindow) infoWindow.close();
      // Open clicked infowindow
      infoWindow = infoWindows[i];
      infoWindow.open(map, marker);
    }
  })(marker, i));
}

function fitToMarkers() {
  map.setZoom(13);
  var bounds = new google.maps.LatLngBounds();
  for(var i = 0; i < markers.length; i++) {
   bounds.extend(markers[i].getPosition());
  }
  map.fitBounds(bounds);
  map.setZoom(13); // zoom out when done so markers on the top can be seen
}

/*
// When Webflow has loaded,
Webflow.push(function() {

    // Resize event
  $(window).resize(function() {
  
    // Do nothing if mobile
    if($(window).width() < 768) return;

    // Resize map if function is defined
    if(typeof mapResize === 'function') mapResize();
  });
  
  
  
});
*/
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map_canvas {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&callback=initialize&libraries=&v=weekly"
      defer
    ></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html>

本教程:Marker Clustering 可能对您的示例更有用。

  1. 包括 MarkerClusterer 脚本:
<script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js"></script>

(或者您可以使用来自不同 CDN 的版本)

  1. 实例化一个MarkerClusterer:
// Add a marker clusterer to manage the markers.
  new MarkerClusterer(map, markers, {
    imagePath:
      "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
  });

proof of concept fiddle

(注意:注释掉 fitToMarkers 调用并设置缩放和居中以便显示集群)

// Variables for Google maps
var map, mapElem, markerImg, infoWindow, marker;
var markers = [], infoWindows = [], 
races = [{lat: 40.7127753, lng: -74.0059728, url:""},
{lat: 40.735657, lng:-74.1723667, url:""}];
var mapOptions = {
  center: races[0], // add center to initialize map
  zoom: 8,          // zoom out so can see cluster
  mapTypeId: 'roadmap',
  //zoom: 13,
  //scrollwheel: false,
  styles: [
{
    "featureType": "administrative",
    "elementType": "labels.text.fill",
    "stylers": [
        {
            "color": "#444444"
        }
    ]
},
{
    "featureType": "landscape",
    "elementType": "all",
    "stylers": [
        {
            "color": "#f2f2f2"
        }
    ]
},
{
    "featureType": "poi",
    "elementType": "all",
    "stylers": [
        {
            "visibility": "off"
        }
    ]
},
{
    "featureType": "road",
    "elementType": "all",
    "stylers": [
        {
            "saturation": -100
        },
        {
            "lightness": 45
        }
    ]
},
{
    "featureType": "road.highway",
    "elementType": "all",
    "stylers": [
        {
            "visibility": "simplified"
        }
    ]
},
{
    "featureType": "road.arterial",
    "elementType": "labels.icon",
    "stylers": [
        {
            "visibility": "off"
        }
    ]
},
{
    "featureType": "transit",
    "elementType": "all",
    "stylers": [
        {
            "visibility": "off"
        }
    ]
},
{
    "featureType": "water",
    "elementType": "all",
    "stylers": [
        {
            "color": "#2bb0e6"
        },
        {
            "visibility": "on"
        }
    ]
}
]
  
};

function initialize() {
  markerImg = {
    url:'https://uploads-ssl.webflow.com/5f58a4616a9e71d63ca059c8/5fa18680b95c219254ad0c9c_place-marker.png',
    size: new google.maps.Size(46, 57),
    anchor: new google.maps.Point(23, 54),
  }
                  
  // Display a map on the page
  mapElem = document.getElementById('map_canvas');
  map = new google.maps.Map(mapElem, mapOptions);
  map.setTilt(45);
  
  

  // Loop through our array of races
  for(i = 0; i < races.length; i++) {
    var race = races[i];
  
    // Generate an infowindow content for the marker
    var infoWindow = new google.maps.InfoWindow();
    infoWindow.setContent(
      '<div class="bg-race"</div>' +
      '<p>'+race.name+'<br>Next race: '+race.date+'</p>' +
      '<a href="'+race.url+'" target="_new"> Race wesbsite </a>'
    );
    infoWindows.push(infoWindow);
  
    // Place a marker on the map
    createMarker(race.lat, race.lng, i);
  }
  // Add a marker clusterer to manage the markers.
  new MarkerClusterer(map, markers, {
    imagePath: 'https://unpkg.com/@google/markerclustererplus@4.0.1/images/m',
  });
  // Center the map fitting all markers on the screen
  // fitToMarkers(); // comment out so can see clustering
}

function createMarker(x, y, i) {
  marker = new google.maps.Marker({
    map: map,
    icon: markerImg,
    position: new google.maps.LatLng(x,y),
    title: races[i].name
  });
  marker._index = i;
  markers.push(marker);
  
  // Click event on marker
  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      // Close last opened infowindow if any
      if(infoWindow) infoWindow.close();
      // Open clicked infowindow
      infoWindow = infoWindows[i];
      infoWindow.open(map, marker);
    }
  })(marker, i));
}

function fitToMarkers() {
  map.setZoom(13);
  var bounds = new google.maps.LatLngBounds();
  for(var i = 0; i < markers.length; i++) {
   bounds.extend(markers[i].getPosition());
  }
  map.fitBounds(bounds);
  map.setZoom(13); // zoom out when done so markers on the top can be seen
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map_canvas {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
        <script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=&v=weekly"
      defer
    ></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html>