gpt4 book ai didi

angular - 将 googlemaps 添加到 angular-cli

转载 作者:太空狗 更新时间:2023-10-29 17:48:51 26 4
gpt4 key购买 nike

我正在尝试将 googlemaps 实现到我的 angular-cli 项目中。我知道有一个“angular2-google-maps”组件 ( github ),但我需要路线和更多自定义功能。

我发现了两种将 map 实现到项目中的方法:

1:stackoverflow : 使用 google api 加载程序 - 但我不知道如何初始化 google-maps...

2:使用 DefinitelyTyped google.maps.d.ts .我将它与 --global (因为 ambient ist deprecated..)一起安装到我的项目中,并将 index.d.ts (用于全局)添加到 src/typings.d.ts 并且可以使用“google.map ..” .ts 文件:

  myLatLng = {lat: -25.363, lng: 131.044};
map:any;

constructor() {
this.map = new google.maps.Map(document.getElementById('map'), {
center: this.myLatLng,
zoom: 4
});
}

但是如果我用 angular-cli 构建它,它会出错:“ReferenceError:未定义谷歌”

有什么想法吗?

最佳答案

这里是将 google maps 组件添加到 angular-cli 项目的分步指南。

第 1 步:从 DefinitelyTyped 安装 google.maps:

typings i dt~google.maps --global --save

第 2 步:如果您安装了较旧的类型,请添加

/// <reference path="../typings/index.d.ts" />

到你的 src/typings.d.ts

第三步:生成新组件

ng g component google-maps

将以下代码添加到:

.ts:

  height = '100px';
myLatLng = {lat: -25.363, lng: 131.044};
map:any;

constructor(private googleApi:GoogleApiService) {}

ngOnInit() {
this.googleApi.initMap().then(() => {

let latlng = new google.maps.LatLng(this.myLatLng.lat, this.myLatLng.lng);

this.map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 4
});

new google.maps.Marker({
position: latlng,
map: this.map,
title: 'Hello World!'
});
});
}

.html :

<div id="map" [style.height]="height"></div>

第四步:生成新服务

ng g service google-maps/shared/google-api

将 GoogleApiService + HTTP_PROVIDERS 添加到 src/main.ts

代码:

const API_KEY = '[insert your code]';
const url = 'https://maps.googleapis.com/maps/api/js?key='+ API_KEY +'&callback=initMap';

@Injectable()
export class GoogleApiService {
private loadMap: Promise<any>;

constructor(private http:Http) {
this.loadMap = new Promise((resolve) => {
window['initMap'] = () => {
resolve();
};
this.loadScript()
});
}

public initMap():Promise<any> {
return this.loadMap;
}

private loadScript() {
let script = document.createElement('script');
script.src = url;
script.type = 'text/javascript';

if (document.body.contains(script)) {
return;
}
document.getElementsByTagName('head')[0].appendChild(script);
}
}

也许您需要从 spec.ts 文件中删除一些行。但随后您可以将 GoogleMapsComponent 添加为指令。

  • 使用路由等进行扩展非常容易。也许如果我有时间,我会将我的 GoogleMapsComponent 的当前版本上传到 github..

关于angular - 将 googlemaps 添加到 angular-cli,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com