2
2

More than 1 year has passed since last update.

GoogleMapのMarkerClustererを使う

Last updated at Posted at 2023-05-26

前回の続きで、
ライブラリを最新にアップデートして、MarkerClustererをimportまでした状態からです
ドキュメント通り書けば行ける話なんですが、理解に時間かかったのでメモです

作業環境

  • Nuxt.js (v2.15.8)
  • @googlemaps/js-api-loader (v1.15.2) を使用
  • @googlemaps/markerclusterer (v2.1.3) を使用

MarkerClustererを使うぞ

ドキュメント通りだと、こうですが

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

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

Nuxtを使っているので、ちょっと工夫します
data()内にthis.mapとかthis.markersを作って実装していると
脳死で書くとこうなる

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

これだとエラーが出るので、
:whale: 公式ドキュメントを見ます、オプションは下記だそうです

{
    algorithm?: Algorithm;
    map?: google.maps.Map;
    markers?: google.maps.Marker[];
    renderer?: Renderer;
    onClusterClick?: onClusterClickHandler;
}

こう書けばいける

this.markerCluster = new MarkerClusterer({ 
    map: this.map,
    markers: this.markers
});

他のオプションを追加する

アルゴリズムを追加する場合はimportに使うアルゴリズムを追記
:whale: 公式ドキュメントのアルゴリズムDEMOはこちら

import { MarkerClusterer, GridAlgorithm } from "@googlemaps/markerclusterer";

algorithmのoptionを追記

this.markerCluster = new MarkerClusterer({ 
    map: this.map,
    markers: this.markers,
    algorithm: new GridAlgorithm({ maxDistance: 4000 }),
});

Clusterのアイコンをカスタマイズしたい場合はrendererを追記します
:whale: 公式ドキュメントのレンダーDEMOはこちら

this.markerCluster = new MarkerClusterer({ 
    map: this.map,
    markers: this.markers,
    algorithm: new GridAlgorithm({ maxDistance: 4000 }),
    renderer: {
        render: ({ count, position }) =>
            new google.maps.Marker({
                icon: {
                    // アイコン画像を使う場合はここにその情報を書く
                },
                label: {
                    text: String(count),
                },
                position,
                // 他のマーカーの上になるよう調整
                zIndex: Number(google.maps.Marker.MAX_ZINDEX) + count,
        }),
    },
});

new google.maps.Marker()は公式リファレンスがあるのでそれぞれのプロパティが使えます
https://developers.google.com/maps/documentation/javascript/reference/marker?hl=ja#MarkerOptions

こんな感じで実装完了です :tada:
GridAlgorithmは見えている範囲外は消してくれるっぽい挙動をするので、とりあえず軽そうという意味で選択してますが
ドキュメント曰く、移動する時にチラつくため、回避したい場合はSuperClusterAlgorithmを使ってね
と書いているっぽいです(英語ワカラナイので翻訳曰くです)

まとめ

オプションの書き方が、書いてないので、元ソースを見たりして大変だった
markerclustererplusの時は見えてない範囲外の処理を別途記載しないと行けなかったので
その点はアルゴリズムで基本装備しているっぽいので楽そうだな~(はたして・・・)

よく分からなくて検索するとnew MarkerClusterer( map, markers );の内容が引っかかるので
これだと違うので、まあまあ実装出来るまで時間かかったよ(;´д`)トホホ…

次の記事

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2