首页 > 解决方案 > 在 ionic4 项目的谷歌地图中添加多个位置标记

问题描述

我正在开发一个 Ionic 项目,该项目的要求是在具有多个标记的离子页面中添加谷歌地图。我遵循了一些 youtube 教程,并成功地添加了带有一个位置标记的谷歌地图。我想添加具有不同纬度和经度值的多个位置标记。

下面是我试过的代码。

HTML:

<ion-content>
<div #mapElement class="map"></div>
</ion-content>

TS:

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

 @Component({
 selector: 'app-test',
 templateUrl: './test.page.html',
styleUrls: ['./test.page.scss'],
})
export class TestPage implements OnInit {
 @ViewChild('mapElement', {static:true}) mapRef: ElementRef;
 constructor() { }

  ngOnInit() {
  }

   ngAfterViewInit() {
  const location = new google.maps.LatLng(17.385044,
  78.486671);

    const options = {
   center:location,
   zoom:10,
   streetViewControl:false,
   mapTypeId:'hybrid'
   };

  const map = new google.maps.Map(this.mapRef.nativeElement,options);
   this.addMarker(location,map);
 }

  addMarker(position,map) {
  return new google.maps.Marker({
    position,
    map
   });
 }

}

请帮助我如何为班加罗尔、钦奈、孟买位置添加不同的标记及其纬度和经度值。

谢谢你。

标签: ionic4

解决方案


正如所建议的那样,您最好的选择是让离子原生组件工作,因为它具有角度/离子感知能力,并且会避免出现问题,就像您已经体验过尝试获得

但是,您需要确定的第一件事是,您正在尝试的方式是,您有

  1. 添加了片段以包含脚本
  2. 给自己一个正确的密钥设置

添加片段

查看 index.html,你应该把它放在结尾之前</body>

<!--Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
-->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

取自这些文档

获取 API 密钥

如今,谷歌地图只是部分免费。您每月可以获得 300 美元的使用费,但是:

  • 你必须有一个 API 密钥,
  • 您的帐户必须有信用卡/计费方式,
  • 并且您应该将 API 密钥限制为仅适用于您的网站/应用程序,以便其他人无法获取您的 API 密钥并在他们自己的网站上使用它

这一切都在这些文档中详细解释。

添加多个标记

制作一些位置:

const locations: any[] = [];
locations.push(new google.maps.LatLng(17.385044, 78.486671));
locations.push(new google.maps.LatLng(17.384412, 78.486671));
locations.push(new google.maps.LatLng(16.312344, 78.486671));
locations.push(new google.maps.LatLng(18.385010, 78.486671));

循环位置并添加它们:

for(let i = 0; i < locations.length; i++) {
  this.addMarker(locations[i],map);
}

仍然有问题?

然后你需要更清楚地解释具体的错误是什么。

只是含糊地说它不起作用,让我们花时间从一百万件事中猜测什么可能是错误的,这是不尊重的。

人们很乐意提供帮助,但您必须让他们轻松。


推荐阅读