Angular10 如何使用 Azure Maps? [解决了]

How to Use Azure Maps with Angular 10? [SOLVED]

我到处搜索有关如何使用 Angular 配置 Azure Maps 的正确文档,但没有找到任何内容。我该怎么做?

(请查看我的自答问题的评论)

由于使用 Angular 配置 Azure Maps 的文档不存在,因此 post 将改为完成该文档。到此 post 结束时,您应该拥有一个带有地图标记的 Azure Maps 工作 Angular 版本。在添加任何代码之前,请按照 Microsoft 网站上的步骤设置您的 Azure Map 密钥:https://docs.microsoft.com/en-us/azure/azure-maps/

创建 Azure Maps 组件的第一步是创建一个新的 Angular 组件并将以下内容添加到您的 .html 文件中:

<div id="azure-map"></div>

该 ID 可用于在 .scss 文件中设置您的组件的样式。

接下来,我们将处理 .ts 文件。首先,让我们设置地图。我们将为地图和坐标添加以下 class 变量:

map: any;
defaultLat: number = 47.608013;  // Seattle coordinates
defaultLng: number = -122.335167;

此输出将坐标发送到地图的父组件:

@Output() outputCoordinates: EventEmitter<number[]> = new EventEmitter<number[]>();

现在我们将创建一个名为 InitMap() 的函数,并在其中添加以下代码片段以初始化底图及其属性:

this.map = new atlas.Map('azure-map', {
  center: [this.defaultLng, this.defaultLat],
  zoom: 12,
  language: 'en-US',
  showLogo: true,
  showFeedbackLink: false,
  dragRotateInteraction: false,
  authOptions: {
    authType: AuthenticationType.subscriptionKey,
    subscriptionKey: 'YOUR_SUBSCRIPTION_KEY_HERE'
  }
});

接下来,我们将在 InitMap() 中添加此代码片段以注册地图点击处理程序和缩放控件:

this.map.events.add('ready', () => {
  // Register the map click handler
  this.map.events.add('click', (e) => {
    this.outputCoordinates.emit([e.position[0], e.position[1]]); // 0 = longitude, 1 = latitude
  });

  //Construct a zoom control and add it to the map.
  this.map.controls.add(new atlas.control.ZoomControl({
    style: ControlStyle.auto,
    zoomDelta: 1
  }), {position: ControlPosition.BottomLeft});
});

我们还必须在 ngOnInit() 内部调用 InitMap() 函数。

下一步是创建允许用户在地图上放置和移动图钉的功能。此函数将擦除地图上的当前标记,设置新标记的坐标,初始化标记拖动处理程序,并设置地图的边界以跟踪新放置的图钉标记。为了处理所有这些操作,我们将添加这个 class 变量:

markersReference: Marker[] = [];

和这个函数:

setMarkers(markers: Marker[]) {
  if (markers && markers.length > 0) {
    this.markersReference = markers;
    this.map.markers.clear();
    let boundsPositions: Array<{lng: number, lat:number}> = [];
    for (let marker of markers) {
      if (marker.latitude && marker.longitude) {
      let htmlMarker = new atlas.HtmlMarker({
        draggable: true,
        position: [marker.longitude, marker.latitude]  // longitude first
      });
      // Register the marker drag handler
      this.map.events.add('dragend', htmlMarker, (e) => {
        var pos = htmlMarker.getOptions().position;
        this.outputCoordinates.emit([pos[0], pos[1]]); // 0 = longitude, 1 = latitude
      });
      boundsPositions.push({lng: marker.longitude, lat: marker.latitude}) // lat, lng
      this.map.markers.add(htmlMarker);
    }
  }
  this.map.setCamera({padding: {top: 20, bottom: 20, left: 20, right: 20}, maxZoom: 16,
    bounds: atlas.data.BoundingBox.fromLatLngs(boundsPositions)});
}

现在我们将添加一个功能,使我们能够将地图焦点集中在放置的图钉上:

centerMapWithCoords(lon: number, lat: number) {
  this.map.setCamera({zoom: 12, maxZoom: 16, center: [lon, lat]});
}

最后,为了获取用户对地图所做的更改,我们将订阅地图主题及其标记。在 class 变量旁边添加这些输入:

@Input() markerDataSubject: Subject<Marker[]> = new Subject<Marker[]>();
@Input() centerMapSubject: Subject<{lng: number, lat: number}> = new Subject<{lng: number, lat: number}>();

接下来,将这些订阅添加到您的 ngOnInit() 中:

this.subscriptions.push((this.centerMapSubject).asObservable().subscribe((coords) =>
  this.centerMapWithCoords(coords.lng, coords.lat)));
this.subscriptions.push((this.markerDataSubject).asObservable().subscribe((markers) =>
  this.setMarkers(markers)));

并在组件关闭时取消订阅:

ngOnDestroy() {
  for (const s of this.subscriptions) {
    s.unsubscribe();
  }
}

总体而言,.ts 文件中的 class 应类似于以下内容:

export class AzureMapComponent implements OnInit {

  @Input() markerDataSubject: Subject<Marker[]> = new Subject<Marker[]>();
  @Input() centerMapSubject: Subject<{lng: number, lat: number}> = new Subject<{lng: number, lat: number}>();

  @Output() outputCoordinates: EventEmitter<number[]> = new EventEmitter<number[]>();

  subscriptions: Subscription[] = [];
  map: any;
  markersReference: Marker[] = [];
  defaultLat: number = 47.608013;  // Seattle coordinates
  defaultLng: number = -122.335167;

  ngOnInit() {
    this.InitMap();
    this.subscriptions.push((this.centerMapSubject).asObservable().subscribe((coords) =>
      this.centerMapWithCoords(coords.lng, coords.lat)));
    this.subscriptions.push((this.markerDataSubject).asObservable().subscribe((markers) =>
      this.setMarkers(markers)));
  }

  //Create an instance of the map control and set some options.
  InitMap() {
    this.map = new atlas.Map('azure-map', {
      center: [this.defaultLng, this.defaultLat],
      zoom: 12,
      language: 'en-US',
      showLogo: true,
      showFeedbackLink: false,
      dragRotateInteraction: false,
      authOptions: {
        authType: AuthenticationType.subscriptionKey,
        subscriptionKey: 'YOUR_SUBSCRIPTION_KEY_HERE'
      }
    });

    this.map.events.add('ready', () => {
      // Register the map click handler
      this.map.events.add('click', (e) => {
        this.outputCoordinates.emit([e.position[0], e.position[1]]); // 0 = longitude, 1 = latitude
      });

      //Construct a zoom control and add it to the map.
      this.map.controls.add(new atlas.control.ZoomControl({
        style: ControlStyle.auto,
        zoomDelta: 1
      }), {position: ControlPosition.BottomLeft});
    });
  }

  setMarkers(markers: Marker[]) {
    if (markers && markers.length > 0) {
      this.markersReference = markers;
      this.map.markers.clear();
      let boundsPositions: Array<{lng: number, lat:number}> = [];
      for (let marker of markers) {
        if (marker.latitude && marker.longitude) {
          let htmlMarker = new atlas.HtmlMarker({
            draggable: true,
            position: [marker.longitude, marker.latitude]  // longitude first
          });
          // Register the marker drag handler
          this.map.events.add('dragend', htmlMarker, (e) => {
            var pos = htmlMarker.getOptions().position;
            this.outputCoordinates.emit([pos[0], pos[1]]); // 0 = longitude, 1 = latitude
          });
          boundsPositions.push({lng: marker.longitude, lat: marker.latitude}) // lat, lng
          this.map.markers.add(htmlMarker);
        }
      }
      this.map.setCamera({padding: {top: 20, bottom: 20, left: 20, right: 20}, maxZoom: 16,
        bounds: atlas.data.BoundingBox.fromLatLngs(boundsPositions)});
    }
  }

  centerMapWithCoords(lon: number, lat: number) {
    this.map.setCamera({zoom: 12, maxZoom: 16, center: [lon, lat]});
  }

  ngOnDestroy() {
    for (const s of this.subscriptions) {
      s.unsubscribe();
    }
  }
}

既然你的 Azure Maps 组件已经完成,你所要做的就是在你想要放置它的任何视图的 .html 中调用你的组件实例并协调所需的输入和输出:

<app-azure-map
    [markerDataSubject]="locationMarkerSubject"
    [centerMapSubject]="centerMapSubject"
    (outputCoordinates)="updateCoordinates($event)">
</app-azure-map>

父组件上的输入主题应如下所示:

locationMarkerSubject: Subject<Marker[]> = new Subject<Marker[]>();
centerMapSubject: Subject<{lng: number, lat: number}> = new Subject<{lng: number, lat: number}>();

并且您的 updateCoordinates() 函数将处理单击地图时从用户输入发回的标记数据。