标记聚类

请选择平台: Android iOS JavaScript

概览

本教程介绍了如何利用标记聚类在地图上显示大量标记。您可以将 @googlemaps/markerclusterer 库与 Maps JavaScript API 配合使用,并将 邻近标记合并成聚类,以简化标记 在地图上的显示方式。

若要了解标记聚类的运作方式,请查看下面的地图。

聚类上的数字表示其包含的标记数量。请注意,在放大任何聚类位置时,聚类上的数字都会减少,其中的各个标记会逐渐显示在地图上。缩小地图会将标记再次合并成聚类。

以下示例显示了创建此地图所需的完整代码。

TypeScript

import { MarkerClusterer } from '@googlemaps/markerclusterer';

async function init() {
    // Request needed libraries.
    const [{ InfoWindow }, { AdvancedMarkerElement, PinElement }] =
        await Promise.all([
            google.maps.importLibrary('maps'),
            google.maps.importLibrary('marker'),
        ]);

    const mapElement =
        document.querySelector<google.maps.MapElement>('gmp-map')!;
    const innerMap = mapElement.innerMap;

    const infoWindow = new InfoWindow({
        content: '',
        disableAutoPan: true,
    });

    // Create an array of alphabetical characters used to label the markers.
    const labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    // Add some markers to the map.
    const markers = locations.map((position, i) => {
        const label = labels[i % labels.length];
        const pinGlyph = new PinElement({
            glyphText: label,
            glyphColor: 'white',
        });

        const marker = new AdvancedMarkerElement({
            position,
            content: pinGlyph,
            gmpClickable: true,
        });

        // markers can only be keyboard focusable when they have click listeners
        // open info window when marker is clicked
        marker.addEventListener('gmp-click', () => {
            const content = document.createElement('div');
            content.textContent = `${String(position.lat)}, ${String(position.lng)}`;
            infoWindow.setContent(content);

            infoWindow.open({
                anchor: marker,
                map: innerMap,
            });
        });
        return marker;
    });

    // Add a marker clusterer to manage the markers.
    new MarkerClusterer({ markers, map: innerMap });
}

const locations = [
    { lat: -31.56391, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 },
    { lat: -33.851702, lng: 151.216968 },
    { lat: -34.671264, lng: 150.863657 },
    { lat: -35.304724, lng: 148.662905 },
    { lat: -36.817685, lng: 175.699196 },
    { lat: -36.828611, lng: 175.790222 },
    { lat: -37.75, lng: 145.116667 },
    { lat: -37.759859, lng: 145.128708 },
    { lat: -37.765015, lng: 145.133858 },
    { lat: -37.770104, lng: 145.143299 },
    { lat: -37.7737, lng: 145.145187 },
    { lat: -37.774785, lng: 145.137978 },
    { lat: -37.819616, lng: 144.968119 },
    { lat: -38.330766, lng: 144.695692 },
    { lat: -39.927193, lng: 175.053218 },
    { lat: -41.330162, lng: 174.865694 },
    { lat: -42.734358, lng: 147.439506 },
    { lat: -42.734358, lng: 147.501315 },
    { lat: -42.735258, lng: 147.438 },
    { lat: -43.999792, lng: 170.463352 },
];

void init();

JavaScript

import { MarkerClusterer } from '@googlemaps/markerclusterer';

async function init() {
    // Request needed libraries.
    const [{ InfoWindow }, { AdvancedMarkerElement, PinElement }] =
        await Promise.all([
            google.maps.importLibrary('maps'),
            google.maps.importLibrary('marker'),
        ]);

    const mapElement = document.querySelector('gmp-map');
    const innerMap = mapElement.innerMap;

    const infoWindow = new InfoWindow({
        content: '',
        disableAutoPan: true,
    });

    // Create an array of alphabetical characters used to label the markers.
    const labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    // Add some markers to the map.
    const markers = locations.map((position, i) => {
        const label = labels[i % labels.length];
        const pinGlyph = new PinElement({
            glyphText: label,
            glyphColor: 'white',
        });

        const marker = new AdvancedMarkerElement({
            position,
            content: pinGlyph,
            gmpClickable: true,
        });

        // markers can only be keyboard focusable when they have click listeners
        // open info window when marker is clicked
        marker.addEventListener('gmp-click', () => {
            const content = document.createElement('div');
            content.textContent = `${String(position.lat)}, ${String(position.lng)}`;
            infoWindow.setContent(content);

            infoWindow.open({
                anchor: marker,
                map: innerMap,
            });
        });
        return marker;
    });

    // Add a marker clusterer to manage the markers.
    new MarkerClusterer({ markers, map: innerMap });
}

const locations = [
    { lat: -31.56391, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 },
    { lat: -33.851702, lng: 151.216968 },
    { lat: -34.671264, lng: 150.863657 },
    { lat: -35.304724, lng: 148.662905 },
    { lat: -36.817685, lng: 175.699196 },
    { lat: -36.828611, lng: 175.790222 },
    { lat: -37.75, lng: 145.116667 },
    { lat: -37.759859, lng: 145.128708 },
    { lat: -37.765015, lng: 145.133858 },
    { lat: -37.770104, lng: 145.143299 },
    { lat: -37.7737, lng: 145.145187 },
    { lat: -37.774785, lng: 145.137978 },
    { lat: -37.819616, lng: 144.968119 },
    { lat: -38.330766, lng: 144.695692 },
    { lat: -39.927193, lng: 175.053218 },
    { lat: -41.330162, lng: 174.865694 },
    { lat: -42.734358, lng: 147.439506 },
    { lat: -42.734358, lng: 147.501315 },
    { lat: -42.735258, lng: 147.438 },
    { lat: -43.999792, lng: 170.463352 },
];

void init();

CSS

html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}

HTML

<html>
    <head>
        <title>Marker Clustering</title>

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY",
            });
        </script>
    </head>
    <body>
        <gmp-map
            center="-28.024,140.887"
            zoom="3"
            map-id="DEMO_MAP_ID"></gmp-map>
    </body>
</html>

为便于说明,本教程利用 locations 数组向地图添加了一组标记。您可以从其他来源获取地图标记。 如需了解详情,请参阅创建标记指南。

添加标记聚类器

请按照以下步骤添加标记聚类器:

  1. 将标记聚类库添加到网页或应用中。该库可在 NPM(地址为 @googlemaps/markerclusterer )以及 GitHub 上的代码库中找到。 选择以下某个选项来安装该库:

    NPM

    使用 NPM 安装 @googlemaps/markerclusterer 库。

    npm install @googlemaps/markerclusterer

    CDN

    以下脚本会从 unpkg.com CDN 加载该库。

    <script src="https://unpkg.com/@googlemaps/markerclusterer/dist/index.min.js"></script>
  2. 在应用中添加标记聚类器。

    以下代码用于向地图添加标记聚类器。选择以下某个选项:

    NPM

    import { MarkerClusterer } from "@googlemaps/markerclusterer";
    
    const markerCluster = new MarkerClusterer({ markers, map });

    CDN

    使用 CDN 访问时,该库可在 markerClusterer 全局下找到。

    const markerCluster = new markerClusterer.MarkerClusterer({ markers, map });

    此示例将 markers 数组传递给 MarkerClusterer。

  3. (可选)自定义标记聚类器,以更改聚类图标外观、聚类算法或点击行为。

自定义标记聚类器

您可以在创建聚类器实例时,通过在 MarkerClustererOptions 对象中传递其他选项来自定义 MarkerClusterer:

以下地图显示了带有自定义聚类图标的标记。

自定义聚类图标

默认情况下,MarkerClusterer 使用 DefaultRenderer 创建 SVG 聚类图标。如需自定义聚类标记的外观,请将实现 Renderer 接口的对象传递给 renderer 选项。

Renderer 接口需要一个 render(cluster, stats, map) 方法,该方法会返回一个 AdvancedMarkerElement(或旧版 google.maps.Marker)。render 方法会接收以下参数:

  • cluster (Cluster): 表示标记组,包括:
    • count:聚类中可见标记的数量。
    • position:聚类的 google.maps.LatLng 中心位置。
    • bounds:聚类的 google.maps.LatLngBounds。
    • markers:聚类中包含的标记数组。
  • stats (ClusterStats):提供当前渲染周期中所有聚类的统计信息,例如 stats.clusters.markers.mean、min、max 和 sum。您可以使用这些值根据聚类的相对大小动态设置聚类的样式。
  • map (google.maps.Map):地图实例。

以下示例定义了一个自定义 renderer,该渲染器会为每个 AdvancedMarkerElement 构建一个圆形 HTML 徽章,并在聚类标记计数超过平均聚类大小时更改其背景颜色。

TypeScript

// Customize the cluster icons using a custom Renderer
    const renderer = {
        render: (
            {
                count,
                position,
            }: { count: number; position: google.maps.LatLng },
            stats: ClusterStats
        ) => {
            // Change color based on the number of markers in the cluster relative to the mean
            const isLargeCluster =
                count > Math.max(10, stats.clusters.markers.mean);
            const clusterClass = isLargeCluster
                ? 'large-cluster'
                : 'small-cluster';

            // Build the HTML content for the Advanced Marker
            const content = document.createElement('div');
            content.classList.add('custom-cluster-icon', clusterClass);
            content.textContent = String(count);

            return new AdvancedMarkerElement({
                position,
                content,
                // Adjust zIndex to be above other markers
                zIndex: 1000 + count,
            });
        },
    };

    // Add a marker clusterer to manage the markers.
    new MarkerClusterer({ markers, map: innerMap, renderer });
}

JavaScript

// Customize the cluster icons using a custom Renderer
    const renderer = {
        render: ({ count, position }, stats) => {
            // Change color based on the number of markers in the cluster relative to the mean
            const isLargeCluster =
                count > Math.max(10, stats.clusters.markers.mean);
            const clusterClass = isLargeCluster
                ? 'large-cluster'
                : 'small-cluster';

            // Build the HTML content for the Advanced Marker
            const content = document.createElement('div');
            content.classList.add('custom-cluster-icon', clusterClass);
            content.textContent = String(count);

            return new AdvancedMarkerElement({
                position,
                content,
                // Adjust zIndex to be above other markers
                zIndex: 1000 + count,
            });
        },
    };

    // Add a marker clusterer to manage the markers.
    new MarkerClusterer({ markers, map: innerMap, renderer });
}

查看完整的自定义呈现器示例

TypeScript

import { MarkerClusterer, ClusterStats } from '@googlemaps/markerclusterer';

async function init() {
    // Request needed libraries.
    const [{ InfoWindow }, { AdvancedMarkerElement, PinElement }] =
        await Promise.all([
            google.maps.importLibrary('maps'),
            google.maps.importLibrary('marker'),
        ]);

    await customElements.whenDefined('gmp-map');

    const mapElement =
        document.querySelector<google.maps.MapElement>('gmp-map')!;
    const innerMap = mapElement.innerMap;

    const infoWindow = new InfoWindow({
        content: '',
        disableAutoPan: true,
    });

    // Create an array of alphabetical characters used to label the markers.
    const labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    // Add some markers to the map.
    const markers = locations.map((position, i) => {
        const label = labels[i % labels.length];
        const pinGlyph = new PinElement({
            glyphText: label,
            glyphColor: 'white',
        });

        const marker = new AdvancedMarkerElement({
            position,
            content: pinGlyph,
            gmpClickable: true,
        });

        marker.addEventListener('gmp-click', () => {
            const content = document.createElement('div');
            content.textContent = `${String(position.lat)}, ${String(position.lng)}`;
            infoWindow.setContent(content);

            infoWindow.open({
                anchor: marker,
                map: innerMap,
            });
        });
        return marker;
    });

    // Customize the cluster icons using a custom Renderer
    const renderer = {
        render: (
            {
                count,
                position,
            }: { count: number; position: google.maps.LatLng },
            stats: ClusterStats
        ) => {
            // Change color based on the number of markers in the cluster relative to the mean
            const isLargeCluster =
                count > Math.max(10, stats.clusters.markers.mean);
            const clusterClass = isLargeCluster
                ? 'large-cluster'
                : 'small-cluster';

            // Build the HTML content for the Advanced Marker
            const content = document.createElement('div');
            content.classList.add('custom-cluster-icon', clusterClass);
            content.textContent = String(count);

            return new AdvancedMarkerElement({
                position,
                content,
                // Adjust zIndex to be above other markers
                zIndex: 1000 + count,
            });
        },
    };

    // Add a marker clusterer to manage the markers.
    new MarkerClusterer({ markers, map: innerMap, renderer });
}

const locations = [
    { lat: -31.56391, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 },
    { lat: -33.851702, lng: 151.216968 },
    { lat: -34.671264, lng: 150.863657 },
    { lat: -35.304724, lng: 148.662905 },
    { lat: -36.817685, lng: 175.699196 },
    { lat: -36.828611, lng: 175.790222 },
    { lat: -37.75, lng: 145.116667 },
    { lat: -37.759859, lng: 145.128708 },
    { lat: -37.765015, lng: 145.133858 },
    { lat: -37.770104, lng: 145.143299 },
    { lat: -37.7737, lng: 145.145187 },
    { lat: -37.774785, lng: 145.137978 },
    { lat: -37.819616, lng: 144.968119 },
    { lat: -38.330766, lng: 144.695692 },
    { lat: -39.927193, lng: 175.053218 },
    { lat: -41.330162, lng: 174.865694 },
    { lat: -42.734358, lng: 147.439506 },
    { lat: -42.734358, lng: 147.501315 },
    { lat: -42.735258, lng: 147.438 },
    { lat: -43.999792, lng: 170.463352 },
];

void init();

JavaScript

import { MarkerClusterer } from '@googlemaps/markerclusterer';

async function init() {
    // Request needed libraries.
    const [{ InfoWindow }, { AdvancedMarkerElement, PinElement }] =
        await Promise.all([
            google.maps.importLibrary('maps'),
            google.maps.importLibrary('marker'),
        ]);

    await customElements.whenDefined('gmp-map');

    const mapElement = document.querySelector('gmp-map');
    const innerMap = mapElement.innerMap;

    const infoWindow = new InfoWindow({
        content: '',
        disableAutoPan: true,
    });

    // Create an array of alphabetical characters used to label the markers.
    const labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    // Add some markers to the map.
    const markers = locations.map((position, i) => {
        const label = labels[i % labels.length];
        const pinGlyph = new PinElement({
            glyphText: label,
            glyphColor: 'white',
        });

        const marker = new AdvancedMarkerElement({
            position,
            content: pinGlyph,
            gmpClickable: true,
        });

        marker.addEventListener('gmp-click', () => {
            const content = document.createElement('div');
            content.textContent = `${String(position.lat)}, ${String(position.lng)}`;
            infoWindow.setContent(content);

            infoWindow.open({
                anchor: marker,
                map: innerMap,
            });
        });
        return marker;
    });

    // Customize the cluster icons using a custom Renderer
    const renderer = {
        render: ({ count, position }, stats) => {
            // Change color based on the number of markers in the cluster relative to the mean
            const isLargeCluster =
                count > Math.max(10, stats.clusters.markers.mean);
            const clusterClass = isLargeCluster
                ? 'large-cluster'
                : 'small-cluster';

            // Build the HTML content for the Advanced Marker
            const content = document.createElement('div');
            content.classList.add('custom-cluster-icon', clusterClass);
            content.textContent = String(count);

            return new AdvancedMarkerElement({
                position,
                content,
                // Adjust zIndex to be above other markers
                zIndex: 1000 + count,
            });
        },
    };

    // Add a marker clusterer to manage the markers.
    new MarkerClusterer({ markers, map: innerMap, renderer });
}

const locations = [
    { lat: -31.56391, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 },
    { lat: -33.851702, lng: 151.216968 },
    { lat: -34.671264, lng: 150.863657 },
    { lat: -35.304724, lng: 148.662905 },
    { lat: -36.817685, lng: 175.699196 },
    { lat: -36.828611, lng: 175.790222 },
    { lat: -37.75, lng: 145.116667 },
    { lat: -37.759859, lng: 145.128708 },
    { lat: -37.765015, lng: 145.133858 },
    { lat: -37.770104, lng: 145.143299 },
    { lat: -37.7737, lng: 145.145187 },
    { lat: -37.774785, lng: 145.137978 },
    { lat: -37.819616, lng: 144.968119 },
    { lat: -38.330766, lng: 144.695692 },
    { lat: -39.927193, lng: 175.053218 },
    { lat: -41.330162, lng: 174.865694 },
    { lat: -42.734358, lng: 147.439506 },
    { lat: -42.734358, lng: 147.501315 },
    { lat: -42.735258, lng: 147.438 },
    { lat: -43.999792, lng: 170.463352 },
];

void init();

CSS

html,
body,
gmp-map {
    height: 100%;
    margin: 0;
    padding: 0;
}

.custom-cluster-icon {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    border: 2px solid white;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-weight: bold;
    font-size: 14px;
    font-family: sans-serif;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

.large-cluster {
    background-color: #ff0000;
}

.small-cluster {
    background-color: #0000ff;
}

HTML

<html>
    <head>
        <title>marker-clustering-custom</title>

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY"
            });
        </script>
    </head>
    <body>
        <gmp-map
            center="-28.024, 140.887"
            zoom="3"
            map-id="DEMO_MAP_ID"></gmp-map>
    </body>
</html>

如需查看其他渲染器示例,请参阅 渲染器使用演示。

修改聚类算法

默认情况下,MarkerClusterer 使用 SuperClusterAlgorithm, 该算法使用 k-d 树对标记进行聚类。您可以通过将算法实例传递给 algorithm 选项,或通过将默认算法的选项传递给 algorithmOptions,来自定义聚类行为。

该库包含以下内置算法:

  • SuperClusterAlgorithm(默认): 快速地理空间点聚类使用 k-d 树。常见选项包括:
    • maxZoom:生成聚类的最大缩放级别(默认值:16)。在高于 maxZoom 的缩放级别下,系统会显示各个标记,而不进行聚类。
    • radius:聚类半径(以像素为单位)(默认值:60)。
    • minPoints:形成聚类所需的最小标记数(默认值:2)。
  • SuperClusterViewportAlgorithm: SuperClusterAlgorithm 的视口过滤变体,仅对当前地图视口内的标记进行聚类,并添加像素内边距(viewportPadding,默认值:60)。
  • GridAlgorithm: 一种基于网格的聚类算法。常见选项包括 maxZoom(默认值:16)、gridSize(网格大小,以像素为单位,默认值:40)和 maxDistance(聚类中心与标记之间的最大距离,以米为单位,默认值:40000)。
  • NoopAlgorithm: 呈现所有标记,而不对其进行聚类。

以下示例使用自定义 radius 和 maxZoom 配置 SuperClusterAlgorithm:

import {MarkerClusterer, SuperClusterAlgorithm} from '@googlemaps/markerclusterer';

const markerCluster = new MarkerClusterer({
  map,
  markers,
  algorithm: new SuperClusterAlgorithm({
    radius: 80,
    maxZoom: 15,
  }),
});

如需比较不同算法的行为方式,请参阅 算法比较演示。

自定义聚类点击行为

默认情况下,点击聚类标记会将地图视口调整为点击的聚类的边界 (map.fitBounds(cluster.bounds))。如需自定义用户点击聚类时发生的情况,请将回调函数传递给 onClusterClick 选项:

const markerCluster = new MarkerClusterer({
  map,
  markers,
  onClusterClick: (event, cluster, map) => {
    // Zoom in by 2 levels centered on the cluster position
    map.setCenter(cluster.position);
    map.setZoom((map.getZoom() ?? 3) + 2);
  },
});

了解详情

您可以在 GitHub 上的代码库中查看更复杂的标记聚类示例,并查看该库的参考文档。