如何将Angular Google Maps与map-icon一起使用

问题描述

我最近开始了一个有角度的项目,需要在地图上显示很多不同的东西。

我最初是从agm(https://github.com/SebastianM/angular-google-maps)开始的,但是我刚刚发现了map-icon(https://github.com/scottdejonge/map-icons),这看起来很棒,因为我需要的所有图标都在这个包中,而我还需要有几种颜色和形式。

是否有将两者关联在一起的方法?现在我不知道怎么做,因为在agm中,您必须提供一个URL,而map-icon似乎可以与html / css一起使用?

解决方法

与其直接依赖第三方库/模块来实现地图,不如直接加载脚本,以便可以在marker icons上使用Google Map的官方文档,将变得更加容易和更好。为此,只需将JS Map脚本加载到index.html中。

以下是一个工作示例供您参考:https://stackblitz.com/edit/angular-map-custom-icons-64402069

index.html

<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
<my-app>loading</my-app>

style.css

html,body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.map {
  height:100%;
}

map-with-marker.component.html

<div #map class="map"></div>

map-with-marker.component.ts

import { Component,OnInit,ViewChild } from "@angular/core";
declare const google: any;

@Component({
  selector: "my-maps",templateUrl: "./map-with-marker.component.html",styleUrls: ["./map-with-marker.component.css"]
})
export class MapComponent implements OnInit {
  @ViewChild("map",{ static: true }) mapElement: any;
  map: any;
  image =
    "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";
  constructor() {}

  ngOnInit() {
    var center = { lat: -33.8569,lng: 151.2152 };
    const mapProperties = {
      center: center,zoom: 11,mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map(
      this.mapElement.nativeElement,mapProperties
    );
    var marker = new google.maps.Marker({
      position: center,map: this.map,icon: this.image
    });

    //adding markers by click
    this.map.addListener("click",e => {
      //Determine the location where the user has clicked.
      this.addMarker(e.latLng);
    });
  }
  addMarker(latLng) {
    var marker = new google.maps.Marker({
      position: latLng,icon: this.image
    });
  }
}