在角度组件中将标记添加到Google地图

问题描述 投票:0回答:1
  • 我正在尝试将标记添加到谷歌地图。
  • 但我面临以下错误。 InvalidValueError:setMap:不是Map的实例;而不是StreetViewPanorama的实例
  • 你能告诉我如何解决它吗?
  • 提供代码和stackblitz如下。

https://stackblitz.com/edit/angular-gmaps-api-suvdaf?file=src/app/map-loader.ts

return MapLoader.load().then((gapi) => {
      this.map = new google.maps.Map(gmapElement.nativeElement, {
        center: new google.maps.LatLng(lat, lng),
        zoom: zoom,
        mapTypeId: type,
       // label: "A"
      });

      this.map1 = new google.maps.Marker({
        label: "A",
        position: { lat: 59.33555, lng: 18.029851 },
        map: map,
        title: 'Hello World!'
      });

      // let markerSimple = new google.maps.Marker({
      //   label: "A",
      //   position: { lat: 59.33555, lng: 18.029851 },
      //   map: map,
      //   title: 'Hello World!'
      // });
    });
javascript html css angular google-maps
1个回答
0
投票

如果我理解了您的问题,则此修改后的代码将添加标记

  import { Injectable } from '@angular/core';
  import { } from '@types/googlemaps';
  declare var window: any;


   // Credits to: Günter Zöchbauer
  // StackOverflow Post: https://stackoverflow.com/a/39331160/9687729

   @Injectable()
   export class MapLoader {

    private static promise;
    map: google.maps.Map;

    public static load() {
      if (!MapLoader.promise) { // load once
      MapLoader.promise = new Promise((resolve) => {
      window['__onGapiLoaded'] = (ev) => {
        console.log('gapi loaded')
        resolve(window.gapi);
     }
      console.log('loading..')
      const node = document.createElement('script');
      node.src = 'https://maps.googleapis.com/maps/api/js?callback=__onGapiLoaded';
      node.type = 'text/javascript';
      document.getElementsByTagName('head')[0].appendChild(node);
    });
  }

  return MapLoader.promise;
}

   initMap(gmapElement, lat, lng, zoom, type) {

     return MapLoader.load().then((gapi) => {
       this.map = new google.maps.Map(gmapElement.nativeElement, {
       center: new google.maps.LatLng(lat, lng),
       zoom: zoom,
       mapTypeId: type,
       // label: "A"
     });
       //after map load add markers
        this.createMarker();
   });
 }

  createMarker() {

     // list of hardcoded positions markers 
      var myLatLngList = {
          myLatLng : [{ lat: 37.76487, lng: -122.41948 }, { lat: 59.33555, lng: 18.029851 }]    
          };

         //iterate latLng and add markers 
        for(const data of myLatLngList.myLatLng){
          var marker = new google.maps.Marker({
              position: data,
              map: this.map,
              title: 'markers'
          });
       }
  };
}
© www.soinside.com 2019 - 2024. All rights reserved.