Angular 7 使用 import Googlemaps
创始人
2024-10-16 20:00:37
0

要在Angular 7中使用Google Maps,你需要遵循以下步骤:

  1. 首先,使用npm安装Google Maps API的类型定义:
npm install --save @types/googlemaps
  1. 在你的Angular项目中,创建一个新的服务以管理Google Maps的加载和初始化。在这个服务中,你可以编写代码来导入和使用Google Maps。
ng generate service google-maps
  1. 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
    });
  }
}
  1. 在需要使用Google Maps的组件中导入并使用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的解决方法。

相关内容

热门资讯

2分钟细说!佛手大菠萝有挂吗,... 2分钟细说!佛手大菠萝有挂吗,德普之星有辅助软件吗,安装教程(有挂透视)准备好在德普之星有辅助软件吗...
大家学习交流!wepoker有... 大家学习交流!wepoker有脚本吗,wepoker插件下载,2025新版教程(有挂辅助)准备好在w...
新手必备!werplan透视挂... 新手必备!werplan透视挂,wepoker透视是真的吗,wpk教程(有挂辅助);最新版2024是...
解密关于!hhpoker是真的... 解密关于!hhpoker是真的还是假的,wepoker的辅助器,实用技巧(有挂软件);hhpoker...
一分钟揭秘!wepoker私人... 一分钟揭秘!wepoker私人局外卦,wepoker安装教程,安装教程(有挂教程);支持2-10人实...
记者发布!wepoker线上大... 记者发布!wepoker线上大神,wpk俱乐部辅助器,第三方教程(有挂辅助);科技安装教程;1367...
一分钟揭秘!wejoker辅助... 一分钟揭秘!wejoker辅助软件价格,wejoker辅助机器人,解密教程(有挂辅助);建议优先通过...
技术分享!wepoker辅助器... 自定义wepoker辅助器最新版本更新内容系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微...
推荐几款新版!德州私人局脚本,... 推荐几款新版!德州私人局脚本,wepoker怎么设置盖牌,2025版教程(有挂攻略);科技安装教程;...
总算明白!德州辅助工具到底怎么... 这是一款非常优秀的wepoker私人局辅助器怎么用 ia辅助检测软件,能够让你了解到wepoker私...