首页 > 解决方案 > 在离子谷歌地图中添加多个标记

问题描述

我正在尝试将谷歌地图集成到离子项目中,并成功在离子页面上显示谷歌地图。但我想在这个谷歌地图上显示多个标记。尝试了不同的代码,但没有得到这个多个标记的东西。下面是我的代码:

html:

<ion-content>

<div #mapElement class="map" >

</div>

.ts 文件:

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

 declare var google;

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
 })
   export class HomePage implements OnInit, AfterViewInit{

@ViewChild('mapElement', { static: true }) mapNativeElement: ElementRef;

constructor() {}

ngOnInit() {
}

ngAfterViewInit(): void {
var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: new google.maps.LatLng(-33.92, 151.25),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) { 
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

}

 }

我想使用类似于下面参考图像的纬度和经度值在地图上添加不同的位置标记

在此处输入图像描述

请帮助我,我该怎么做。谢谢你

标签: google-mapsionic4

解决方案


在一个项目中,我需要做同样的事情,所以我做了这个功能。因此,您只需在要打印的列表中放置一个 for/foreach 即可。

希望这对您有所帮助。

private createMarker(position, label, element, icon) {

if (this.map != undefined) {
  let marker = new google.maps.Marker({
    position: position,
    map: this.map,
    icon: {
      url: icon, // url
      scaledSize: new google.maps.Size(40, 40), // scaled size
    }

  });
  google.maps.event.addListener(marker, 'click', function () {

    var infowindow = new google.maps.InfoWindow({
      content: "content"
    });
    infowindow.open(this.map, marker);

  });
} else {
  console.log("map is undefined");
}

}

使用循环,您应该能够使用上面的函数正确创建标记:

this.markers.forEach(element => {

  this.infomarkers.forEach(info => {

    if (element.id == info.id) {

      this.createMarker(element.position, element.label, info, element.icon);

    }

  });

});

推荐阅读