首页 > 解决方案 > 使用 Angular 和 agm 获取用户地理位置并将 Google 热图居中

问题描述

我正在尝试呈现以当前用户位置为中心的 Google 热图。

我有点新手。我已经设置了基本方法,但我很难在正确的时间调用这些方法。我知道 Angular 中有各种生命周期钩子,但我认为这不是我想要的(?)。

我基本上想在渲染地图之前先获取用户的地理位置,然后将用户的位置作为地图的属性之一来渲染地图。

目前地图通过我的视图渲染:

<agm-map (mapReady)="onMapLoad($event)">
  <agm-marker></agm-marker>
</agm-map>

但我想通过组件来做到这一点。所以函数调用是;第onGetLocatio()一个回调到onShowPosition(),然后 finallyonMapLoad()必须被调用。这是正确的方法(调用顺序),还是有更好的方法?

这是我的控制器方法:

onGetLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(this.onShowPosition);
  } else {
    console.log('Not supported by browser!');
  }
}

onShowPosition = (position: any) => {
  this.currentLat = position.coords.latitude;
  this.currentLong = position.coords.longitude;

  this.currentLatLng = new google.maps.LatLng(this.currentLat, this.currentLong);
  console.log(this.currentLatLng);
}

onMapLoad(mapInstance: google.maps.Map) {
  this.map = mapInstance;
  this.map.setCenter(this.currentLatLng);

  this.heatmap = new google.maps.visualization.HeatmapLayer({
    map: this.map,
    data: this.heatMapData
  });
}

先感谢您!

标签: angulargoogle-maps

解决方案


推荐阅读