gpt4 book ai didi

google-maps - 如何将 Google Maps API 集成到 Angular 2 组件中

转载 作者:太空狗 更新时间:2023-10-29 16:53:45 25 4
gpt4 key购买 nike

我有一个在文件 comp.ts 中定义的 Angular 2 组件,如下所示:

import {Component} from 'angular2/core';

@component({
selector:'my-comp',
templateUrl:'comp.html'
})

export class MyComp{
constructor(){
}
}

因为我想让组件显示谷歌地图,所以我在文件 comp.html 中插入了以下代码:

<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>

</html>

此代码已从此链接复制 http://www.w3schools.com/googleAPI/google_maps_basic.asp .问题是组件不显示 map 。我做错了什么?

最佳答案

是的,你可以这样做。但是 typescript 编译器会出错,所以不要忘记隐式声明 google 变量。

declare var google: any;

在组件导入后立即添加此指令。

import { Component, OnInit } from '@angular/core';
declare var google: any;

@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"), mapProp);
}
}

关于google-maps - 如何将 Google Maps API 集成到 Angular 2 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37326572/

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