将按钮添加到Google Maps Angular2

5

我是Angular的新手,我有一个Web应用程序,可以显示全屏谷歌地图。我想在Google地图布局中添加一个“注销”按钮(不作为标头)。

我知道使用javascript Google Maps API很容易实现,例如:

var Logout = document.getElementById('Logout');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(Logout);

但是使用 AGM - Angular Google Maps,我没有找到如何实现。

现在我有了这个:

map.component.html

<button id="Logout" [(ngModel)]="logoutButton" class="toggle-button controls button" (click)="logout()">Logout</button>

<agm-map [latitude]="lat" [longitude]="lng" [zoom]=12 [mapTypeControl]="true" (boundsChange)="centerChanged($event)" (idle)="loadParkings()" >

    <agm-marker *ngFor="let park of parkings" [latitude]="park.location[0]" [longitude]="park.location[1]"></agm-marker>
</agm-map>

map.component.ts

import {GoogleMapsAPIWrapper} from '@agm/core';

declare var google: any;

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})

export class MapComponent implements OnInit {
  lat: number;
  lng: number;
  map: any;
  logoutButton: any;

  constructor(
    public mapApi: GoogleMapsAPIWrapper) {}

  ngOnInit(): void {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
      });
    } else {
      this.lat = 47.2275654;
      this.lng = -1.3849729;
    }
  }


  logout() {
    this.authenficationService.logout();
    this.router.navigate(['/login']);
  }
}
2个回答

12
我几天前找到了解决办法,看起来与你的答案相似。我使用了事件(mapReady),它提供了本地地图的实例。
这是我如何在地图中显示搜索框的方式。 map.component.html
<agm-map [latitude]="lat" [longitude]="lng" [zoom]=12 [mapTypeControl]="true" (boundsChange)="centerChanged($event)" (idle)="loadParkings()"
    (mapReady)="mapReady($event)" (boundsChange)="boundsChanged($event)">
    <button id="Settings" class="toggle-button controls button" [hidden]="hideSettings">
        <mat-icon aria-hidden="true">settings</mat-icon>
    </button>
    <button id="Profile" class="toogle-button controls button" (click)="profileClicked()">
        <mat-icon aria-hidden="true">account_circle</mat-icon>
    </button>
    <button id="Logout" class="toggle-button controls button" (click)="logout()">Logout</button>
    <input id="Map-Search" class="controls" type="text" placeholder="Search Box">
    <agm-marker *ngFor="let park of parkings" [latitude]="park.location[0]" [longitude]="park.location[1]"></agm-marker>
</agm-map>

map.component.ts

declare const google: any;

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css'],
})

export class MapComponent {
    map: any;
    searchBox: any;

    [...]

    mapReady(event: any) {
        this.map = event;
        const input = document.getElementById('Map-Search');
        this.searchBox = new google.maps.places.SearchBox(input);
        this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(document.getElementById('Settings'));
        this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(document.getElementById('Profile'));
        this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
        this.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(document.getElementById('Logout'));

        this.searchBox.addListener('places_changed', () => this.goToSearchedPlace());
    }

    goToSearchedPlace() {
        const places = this.searchBox.getPlaces();
        if (places.length === 0) {
        return;
        }
        const bounds = new google.maps.LatLngBounds();
        places.forEach((place) => {
        if (place.geometry.viewport) {
            bounds.union(place.geometry.viewport);
        } else {
            bounds.extend(place.geometry.location);
        }
        });
        this.map.fitBounds(bounds);
    }
}

谢谢。非常好用。我在想,是否有一种方法可以在动态创建元素时将元素添加到地图中,例如使用*ngIf? - Khasan 24-7
2
此处所述,红色代码示例中,您可能需要导入“places”库。在您的模块中可以这样写:AgmCoreModule.forRoot({ libraries: ['places'] })。这将在window对象上添加google.maps.places - Brampage
我在想,是否有什么改变,因为我的AgmMap上没有.controls - Ian
好的,所以只是移除AgmMap的类型仍然可以工作,但我需要改变对boundsChange事件的反应方式。 - Ian
我尝试在我的AGM地图上添加一个名为“设置位置”的按钮,但是当我倾斜或移动地图时,它会闪烁。有什么帮助吗? - Ravi Mehta
谢谢,这给了我一个想法,如何在我的Angular应用程序中使用相同的方法 - 使用ID标记我的元素,并使用document.getElementById()将其添加到我的地图控件中,以向本地TypeScript Google Maps库添加自定义控件。 - Patronaut

0

我几天前也遇到了同样的问题。我不确定这是否是正确的方法。您可以通过GoogleMapsAPIWrapper中的getNativeMap()获取地图。然后将其分配给任何类型的变量,否则它无法找到控件:

view-more-button.component.ts

import { Component, OnInit } from '@angular/core';
import { GoogleMapsAPIWrapper } from '@agm/core/services/google-maps-api-wrapper';
declare var google: any;

@Component({
  selector: 'app-view-more-button',
  templateUrl: './view-more-button.component.html',
  styleUrls: ['./view-more-button.component.css']
})
export class ViewMoreButtonComponent implements OnInit {

  private _isMoreMap: boolean;

  constructor(private _wrapper: GoogleMapsAPIWrapper) {
    this._isMoreMap = true;
  }

  ngOnInit() {
    this._wrapper.getNativeMap().then((m) => {
      // m type doesnt have controls declared. So need to store it to <any> first then use controls
      var nativeMap: any;
      nativeMap = m;
      nativeMap.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById("view-more-button"));
    });
  }

  private _click() {
    ...
  }

}

view-more-button.component.html

<button class="btn btn-primary" (click)="_click()" id="view-more-button">
  View More Map
</button>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接