下面是一个使用Angular 2和Google Maps API在Google地图中创建多个矩形并刷新数据位置的示例代码:
MapComponent
,并在map.component.ts
文件中添加以下代码:import { Component, OnInit } from '@angular/core';
// 在index.html中添加
declare var google: any;
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
map: any;
rectangles: any[] = [];
data: any[] = [
{ id: 1, lat: 37.7749, lng: -122.4194 },
{ id: 2, lat: 34.0522, lng: -118.2437 },
{ id: 3, lat: 39.9526, lng: -75.1652 }
];
constructor() { }
ngOnInit() {
this.initMap();
this.createRectangles();
}
initMap() {
const mapOptions = {
center: new google.maps.LatLng(37.7749, -122.4194),
zoom: 10
};
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
createRectangles() {
for (const location of this.data) {
const rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: this.map,
bounds: {
north: location.lat + 0.1,
south: location.lat - 0.1,
east: location.lng + 0.1,
west: location.lng - 0.1
}
});
this.rectangles.push(rectangle);
}
}
updateRectangles() {
for (let i = 0; i < this.rectangles.length; i++) {
const location = this.data[i];
const bounds = {
north: location.lat + 0.1,
south: location.lat - 0.1,
east: location.lng + 0.1,
west: location.lng - 0.1
};
this.rectangles[i].setBounds(bounds);
}
}
}
map.component.html
文件中添加以下代码:
app.module.ts
文件中将MapComponent
添加到declarations
和exports
数组中。import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MapComponent } from './map.component';
@NgModule({
declarations: [
AppComponent,
MapComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
请记得替换代码中的YOUR_API_KEY
为你自己的Google Maps API密钥。