【问题标题】:How to use Angular google maps with map-icon如何使用带有地图图标的 Angular 谷歌地图
【发布时间】:2020-10-17 11:45:20
【问题描述】:

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

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

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

【问题讨论】:

    标签: angular google-maps angular-google-maps


    【解决方案1】:

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

    这是一个工作示例供您参考: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%;
    }
    

    ma​​p-with-marker.component.html

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

    ma​​p-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,
          map: this.map,
          icon: this.image
        });
      }
    }
    
    

    【讨论】:

    • 我正在考虑这样做,我唯一遇到的问题是:标记集合来自可观察的集合(会改变),我不确定如何同步它。你会怎么做?另外,我不太喜欢在 typescript 文件中创建 HTML 元素,它会带来很多其他问题(比如:谁会取消订阅这个点击事件监听器?)
    猜你喜欢
    • 1970-01-01
    • 2016-11-25
    • 2013-01-29
    • 2016-09-20
    • 2020-03-09
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多