在 Angular 15 中实时更新谷歌地图标记位置需要使用谷歌地图API和Angular 15的组件。以下是示例代码,它展示了如何实现一个实时更新标记位置的Angular 15谷歌地图应用程序。
要使用谷歌地图API和Angular 15的组件,需要在应用程序中安装必要的依赖。
npm install @types/googlemaps --save-dev
npm install @agm/core --save
在index.html文件中使用以下脚本标记引入谷歌地图API。
在使用AGM库前,在模块中导入AGM库,并在组件模板中使用AGM组件。
// app.module.ts
import { AgmCoreModule } from '@agm/core';
@NgModule({
imports: [
AgmCoreModule.forRoot({
apiKey: 'API_KEY'
})
],
...
})
// app.component.html
为了在实时更新中更新标记位置,需要在组件中使用setInterval函数定时更新标记位置。
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Real-time Updating Google Maps in Angular 15';
lat = 40.71448;
lng = -74.00598;
zoom = 12;
constructor() {
setInterval(() => {
this.lat += Math.random() * 0.01;
this.lng -= Math.random() * 0.01;
}, 1000);
}
}
在上面的代码中,使用setInterval函数每秒更新一次标记位置。
最终,就能实现Angular 15中实时更新谷歌地图标记位置的应用程序。