要在Angular 7中使用Google Maps,你需要遵循以下步骤:
npm install --save @types/googlemaps
ng generate service google-maps
google-maps.service.ts
文件中,导入Google Maps API并编写相关代码:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class GoogleMapsService {
constructor() {
this.loadGoogleMaps();
}
loadGoogleMaps() {
if (!window.google) {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY';
document.body.appendChild(script);
}
}
// 在需要使用Google Maps的组件中调用此方法来初始化地图
initMap() {
const map = new window.google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
}
GoogleMapsService
:import { Component, OnInit } from '@angular/core';
import { GoogleMapsService } from './google-maps.service';
@Component({
selector: 'app-my-component',
template: '',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
constructor(private googleMapsService: GoogleMapsService) { }
ngOnInit() {
this.googleMapsService.initMap();
}
}
请确保将YOUR_API_KEY
替换为你自己的Google Maps API密钥。
以上就是在Angular 7中使用Google Maps的解决方法。