代码之家  ›  专栏  ›  技术社区  ›  Tankske

使用带有动态src属性的google角度嵌入地图

  •  1
  • Tankske  · 技术社区  · 8 年前

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

    • 位置是固定的,因此链接存储在数据库中
    • 与google地图API相比,google嵌入式地图API的API限制更高。

    使用嵌入式映射api有一个陷阱,就是使用iFrame由于安全原因(xss),实现起来有点困难虽然我使用的是Angulars域消毒剂,但仍然难以分配源变量。

    用静态引用替换动态引用有效,在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>
    

    App-component.html软件

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

    API参考: 消毒剂: https://angular.io/api/platform-browser/DomSanitizer 谷歌嵌入式地图API: https://developers.google.com/maps/documentation/embed/guide 谷歌地图API: https://developers.google.com/maps/documentation/javascript/adding-a-google-map

    0 回复  |  直到 8 年前
    推荐文章