使用带有动态src-attribute的角度的谷歌嵌入地图

时间:2018-05-27 15:10:16

标签: angular google-maps

我正在使用angular(6),我正在编写一个可重复使用的组件来显示嵌入式谷歌地图。主要原因是:

  • 位置已修复,因此链接存储在数据库中
  • 谷歌嵌入式地图API与谷歌地图API相比,API限制更高。

使用嵌入式地图api作为iFrame的使用存在一个缺陷。由于安全原因(xss),实现起来有点困难。虽然我正在使用Angulars DomSanitizer,但我仍然很难分配源变量。

用静态引用替换动态引用有效,在iFrame中将[src]更改为src会给我一个路由错误..

角度组件

    import { Component, OnInit, Input } from '@angular/core';
    import {DomSanitizer} from '@angular/platform-browser';

    @Component({
      selector: 'app-google-map-embed',
      templateUrl: './google-map-embed.component.html',
      styleUrls: ['./google-map-embed.component.css']
    })
    export class GoogleMapEmbedComponent implements OnInit {

      private placeUri:string = "";
      private key:String = "My_Key"
      @Input() type:string = "";

      constructor(public sanitizer:DomSanitizer) { }

      ngOnInit() {
        console.log(this.type);
        switch(this.type){
          case 'place':
            this.placeUri = "https://www.google.com/maps/embed/v1/place?key=" + this.key +
              "&q=Fairmont+Empress,Victoria+BC&attribution_source=Google+Maps+Embed+API&attribution_web_url=http://www.fairmont.com/empress-victoria/&attribution_ios_deep_link_id=comgooglemaps://?daddr=Fairmont+Empress,+Victoria,+BC";
            break;
          case 'directions':
            this.placeUri = "https://www.google.com/maps/embed/v1/directions\
                              ?key=YOUR_API_KEY\
                              &origin=Oslo+Norway\
                              &destination=Telemark+Norway\
                              &avoid=tolls|highways"
        }
      }

      mapsURL() {
        console.log(this.sanitizer.bypassSecurityTrustUrl(this.placeUri));
        return this.sanitizer.bypassSecurityTrustUrl(this.placeUri);
      }

    }

角度模板

    <p>Generated URL for debugging purposes: {{placeUri}}</p>

    <iframe
      width="600"
      height="450"
      frameborder="0" style="border:0"

      [src]="mapsURL()" allowfullscreen>
    </iframe>

应用-component.html

    <app-google-map-embed type='place'></app-google-map-embed>

API的参考资料: DomSanitizer:https://angular.io/api/platform-browser/DomSanitizer Google嵌入式地图API:https://developers.google.com/maps/documentation/embed/guide Google地图API:https://developers.google.com/maps/documentation/javascript/adding-a-google-map

0 个答案:

没有答案