0

I have a working map with AdvancedMarkerElements, but it's completely killing the browser as soon as there are a few hundred markers. So I'm trying to add MarkerClusterer, but I just won't get it to work whatever I try - feel quite stupid now.

I've tried to add MarkerClusterer Library from several sources with different methods and looked at tons of examples, but I always end up with an error saying "MarkerClusterer is not defined" or similiar.

<script src="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js"></script>
<div id="map"></div>
<script type="text/javascript">
  (g => {
    var h, a, k, p = "The Google Maps JavaScript API",
      c = "google",
      l = "importLibrary",
      q = "__ib__",
      m = document,
      b = window;
    b = b[c] || (b[c] = {});
    var d = b.maps || (b.maps = {}),
      r = new Set,
      e = new URLSearchParams,
      u = () => h || (h = new Promise(async (f, n) => {
        await (a = m.createElement("script"));
        e.set("libraries", [...r] + "");
        for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]);
        e.set("callback", c + ".maps." + q);
        a.src = `https://maps.${c}apis.com/maps/api/js?` + e;
        d[q] = f;
        a.onerror = () => h = n(Error(p + " could not load."));
        a.nonce = m.querySelector("script[nonce]")?.nonce || "";
        m.head.append(a)
      }));
    d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n))
  })
  ({
    key: "",
    v: "weekly"
  });

  async function initMap() {
    const {
      Map
    } = await google.maps.importLibrary("maps");
    const {
      AdvancedMarkerElement
    } = await google.maps.importLibrary("marker");
    const center = {
      lat: 50.5459719,
      lng: 10.0703129
    };
    const map = new Map(document.getElementById("map"), {
      zoom: 6.6,
      center,
      mapId: "4504f8b37365c3d0",
    });
    geocoder = new google.maps.Geocoder();
    markers = [];
    for (const property of properties) {
      if (property.lat != '' && property.lng != '') {
        var marker = new google.maps.marker.AdvancedMarkerElement({
          map: map,
          content: buildContent(property),
          position: new google.maps.LatLng(property.lat, property.lng),
          title: property.name,
        });
        marker.addListener("gmp-click", () => {
          toggleHighlight(marker, property);
        });
        markers.push(marker);
      }
    }
    var mc = new MarkerClusterer(map, markers)
  }

  function toggleHighlight(markerView, property) {
    if (markerView.content.classList.contains("highlight")) {
      markerView.content.classList.remove("highlight");
      markerView.zIndex = null;
    } else {
      markerView.content.classList.add("highlight");
      markerView.zIndex = 1;
    }
  }

  function buildContent(property) {
    const content = document.createElement("div");

    content.classList.add("property");
    content.innerHTML = `
    <div class="icon user" id="wb${property.id}">
        <i aria-hidden="true" class="fa fa-icon fa-user" title="${property.name} (${property.type})"></i>
        <span class="fa-sr-only">${property.name} (${property.type})</span>
    </div>
    <div class="details">
        <div class="name">${property.name}</div>
        <div class="address">${property.address}</div>
        <div class="mail"><a href="mailto:${property.mail}">${property.mail}</a></div>
        <div class="phone"><a href="tel:${property.phone}">${property.phone}</a></div>
        <div class="features">
        </div>
    </div>
    `;
    return content;
  }
</script>
2
  • i see where you are importing AdvancedMarkerElement and Map, but i don't see you importing MarkerClusterer. did you simply forget the import? see the google docs example Commented May 27 at 14:51
  • I tried adding an import, but that resulted in an error saying it can only be used in a module. when I changed the script type to module, it produced errors with the geocoder. I was lost there. Commented Jun 11 at 8:13

1 Answer 1

0

I finally rebuild it with a different working example using the import-method and changed the way the position is added, without the Geocoder.

Also, in case it might be useful for someone: The map was so terribly slow because it used FontAwesome-Icons, which resulted in strange JS-errors (while being displayed correctly) - as soon as I replaced them with static SVG, it was fine.

One thing though that is being ignored without an error: The MarkerClusterer-Options don't work (minimumClusterSize: 10, maxZoom: 15) - any ideas how to do this correctly, or is it just broken?


<div id="map"></div>
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
({key: "", v: "weekly"});</script>
<script type="module">
import { MarkerClusterer } from "https://cdn.skypack.dev/@googlemaps/[email protected]";
async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
  const center = { lat: 50.5459719, lng: 10.0703129 };
  const map = new Map(document.getElementById("map"), {
    zoom: 6.6,
    center,
    mapId: "4504f8b37365c3d0",
  });
  const labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const markers = properties.map((property, i) => {
    const label = labels[i % labels.length];
    const marker = new google.maps.marker.AdvancedMarkerElement({
      position: new google.maps.LatLng(property.lat,property.lng),
      content: buildContent(property),
      title: property.name,
    });
    marker.addListener("gmp-click", () => {
        toggleHighlight(marker, property);
    });
    return marker;
  });

  const markerCluster = new MarkerClusterer({ markers:markers, map:map, options:{minimumClusterSize: 10, maxZoom: 15} });

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.