我正在尝试在Angular6组件中实现Google Map。但是,我无法这样做。我已经从-
嵌入了Google Map JavaScripthttps://developers.google.com/maps/documentation/javascript/examples/rectangle-simple
我的地图无法加载。
app.component.html
<div id="map"></div>
app.component.ts
import { Component, OnInit,AfterViewInit } from '@angular/core';
import { ViewChild, ElementRef, Renderer } from '@angular/core'
const url = '../../../assets/googlemap.js'
@Component({
selector: 'app-search-api',
templateUrl: './search-api.component.html',
styleUrls: ['./search-api.component.scss']
})
export class SearchApiComponent implements OnInit, AfterViewInit {
PhotoGoogleSDK: any;
constructor() { }
ngOnInit() {
this.loadScript();
}
// ------------------ Javascript code ----------------
public loadScript() {
console.log('preparing to load...')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
googlemap.js
var citymap = {
chicago: {
center: {lat: 41.878, lng: -87.629},
population: 2714856
}
};
function initMap() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 4,
center: {lat: 37.090, lng: -95.712},
mapTypeId: 'terrain'
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
}
}
var tag = document.createElement('script');
tag.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyCXNFDDBMRr6YX8LJtltvEbQJsLA&callback=initMap";
tag.defer = true;
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
答案 0 :(得分:0)
要在angular2 +中实现Google地图,您必须执行以下操作。
现在您的component.ts中将const google声明为任何
declare const google: any;
现在在组件的html中,添加一个具有ID的新div
<div id="google_map" class="map"></div>
public initializeMap() {
let _map = document.getElementById('google_map');
let lat = YOUR_INITIAL_LATITUDE;
let lng = YOUR_INITIAL_LONGITUDE;
let pos = new google.maps.LatLng(lat, lng);
let map = new google.maps.Map(_map, {
center: pos,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
}
请注意,您可能需要安装Google输入。
npm install --save @types/googlemaps