标记聚合器不是一个构造函数。

3

我正在尝试在我的应用程序中实现标记聚合器。 我已经在项目中安装了'@google/markerclusterer'并按照下面所示导入了它。 但是,我收到了错误消息:core.js:4002 ERROR TypeError: _google_markerclusterer__WEBPACK_IMPORTED_MODULE_7__不是构造函数。 我不知道为什么会出现这种情况,因为它应该是一个构造函数。 这是我的代码。

import * as MarkerClusterer from '@google/markerclusterer';

在initMap()函数内部

    for (var i = 0; i < features.length; i++) {

      const infowindow = new google.maps.InfoWindow({
        content: features[i].content
      });

      const marker2 = new google.maps.Marker({
        position: features[i].position,
        icon: icons[features[i].type].icon,
        animation: google.maps.Animation.DROP,
        map: map
      });

      marker2.addListener('click', () => {
        marker2.setAnimation(google.maps.Animation.BOUNCE);
        setTimeout(() => {
          marker2.setAnimation(null);
        }, 1000);
        infowindow.open(map, marker2);
      });
      const markerCluster = new MarkerClusterer(map, marker2,
        { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
    }

2
尝试使用以下代码导入MarkerClusterer:import MarkerClusterer from '@google/markerclusterer'; 而不是使用*。 - MukulSharma
@MukulSharma 我从这里得到了两个错误:TypeError: marker.getPosition 不是一个函数,位于 MarkerClusterer.isMarkerInBounds_ 和 Cannot create property 'isAdded' on string 'https://developers.google.com/maps/documentation/javascript/examples/full/images/info-i_maps.png',位于 MarkerClusterer.pushMarkerTo_ (markerclusterer.esm.js:429)。 - Jonathan
https://developers.google.com/maps/documentation/javascript/marker-clustering#cdn - Joseph Wambura
3个回答

3
<script src="https://unpkg.com/@googlemaps/markerclusterer/dist/index.min.js"></script>` 

请在您的函数initMap中使用此代码。
const markerCluster = new markerClusterer.MarkerClusterer({ map, markers });

0
为了突出来自@MukulSharma的评论。可以考虑改为:
import * as MarketClusterer '@google/markerclusterer' 

做这个

import MarkerClusterer from '@google/markerclusterer'

0

这是一个类型错误。Typescript 不知道如何定位 typings。你尝试过 @types/markerclustererplus 吗?

每当我安装一个库时,我总是尽量寻找类型定义。而且,像 Google Analytics 和 Googlemaps 这样的库可能会很麻烦,所以将它们添加到 src/tsconfig.json 中的 tsconfig.json 可以帮助解决问题:

"types": [
  "googlemaps",
  "google.analytics",
  "node"
]

在你的项目根目录下的 typings.d.ts 文件中:

declare var MarkerClusterer: any;

declare module 'google-maps' {
  export = google.maps;
}

或将它放在你的中间

import { ... } from '@angular/core';

declare var MarkerClusterer: any;

@Component()

如果您不想做 typings.d.ts 或者 src/tsconfig.json,可以尝试其他选项。Angular/Typescript 很挑剔。


喜欢这个答案... 我从控制台没有收到任何错误,但是聚类仍然不会出现在地图上。 - Jonathan
为什么它没有出现我无法说。您是否尝试使用Google Chrome的Sources逐步执行它?设置断点并逐步查看是否有值。这里是可能的答案:https://stackoverflow.com/a/49301912/4208845 - Thomas Cayne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接