【问题标题】:new google.maps.Map(document.getElementById('agmmap'),{}) causes agm map to disappearnew google.maps.Map(document.getElementById('agmmap'),{}) 导致 agm 地图消失
【发布时间】:2020-10-26 12:15:11
【问题描述】:

我正在尝试将 google 地方库与 agm 地图一起使用。

html

<agm-map #map id="map" [mapTypeId]="'terrain'" [latitude]="lat" [longitude]="lng" [scrollwheel]="false" style="height: 300px">
  <agm-marker name="latlong" [latitude]="lat" [longitude]="lng" (dragEnd)="markerDragEnd(latitude, longitude, $event)" [markerDraggable]="true">
  </agm-marker>
</agm-map>

ts

@ViewChild(AgmMap, {
  static: true
}) maps: AgmMap;

searchNearbyLocations() {
  var pyrmont = new google.maps.LatLng(this.maps.latitude, this.maps.longitude);
  var request = {
    location: pyrmont,
    radius: this.radius,
    type: this.orgtype
  };

  var map = new google.maps.Map(document.getElementById('map'), {
    center: pyrmont,
    zoom: 15
  });
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, this.callback);
}

callback(results, status) {
  console.log(JSON.stringify(results));
}

这段代码导致我的 agm 地图从视图中消失

var map = new google.maps.Map(document.getElementById('map'), {
  center: pyrmont,
  zoom: 15
});

这里发生了什么?新创建的地图会取代我的 agm 吗?如何解决这个问题?

【问题讨论】:

  • 您必须提供一个minimal reproducible example 以允许重现该问题。此外,网络上有很多关于如何按照您的要求执行操作的示例,但我发现没有一个示例可以指导您按照自己的方式初始化地图对象。

标签: javascript html angular typescript agm


【解决方案1】:

可能是因为您针对的是同一个 DOM 元素(Google 设置了它的 html)。现在,我对 Angular 并不熟悉,但您可能不需要启动新地图,因为您已经拥有一张(来自 AGM)。

我找到了a comment,它解释了如何获取地图的实例。基于此:

<agm-map (mapReady)="onMapReady($event)"></agm-map>
public onMapReady(e) {
  this.map = e;
}

所以在searchNearbyLocations中,你可以使用this.map,而不是创建新地图,像这样:

searchNearbyLocations(){
  var pyrmont = new google.maps.LatLng(this.maps.latitude,this.maps.longitude);
  var request = {
    location: pyrmont,
    radius:this.radius,
    type: this.orgtype
    
  };

  var service = new google.maps.places.PlacesService(this.map);
  service.nearbySearch(request, this.callback);
}

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2012-03-24
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    相关资源
    最近更新 更多