【问题标题】:Adding multiple location markers in google map in ionic4 project在 ionic4 项目的谷歌地图中添加多个位置标记
【发布时间】:2020-01-21 03:32:57
【问题描述】:

我正在开发一个 Ionic 项目,该项目的要求是在具有多个标记的 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
   });
 }

}

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

谢谢。

【问题讨论】:

  • 如果您使用 Ionic,我建议您使用原生 Google Maps 插件而不是纯 JavaScript API。请参阅here 了解如何安装和here 了解带有标记的示例
  • 谢谢@andypotato,我会试试这个,让你知道
  • 嗨@andypotato,它不适合我。我是离子的新手。你能帮忙写几盎司的代码吗?谢谢

标签: ionic4


【解决方案1】:

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

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

  1. 添加了 sn-p 以包含脚本
  2. 为自己设置了正确的密钥

添加sn-p

查看index.html,你应该把它放在&lt;/body&gt;的末尾之前

<!--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>

取自these docs

获取 API 密钥

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

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

这个都有详细解释in these docs

添加多个标记

制作一些地点:

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);
}

还有问题吗?

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

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

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

【讨论】:

  • 嗨@rtpHarry,谢谢你的回答。如您的回答中所述,我使用了 google maps api 并生成了一个 api 密钥。使用一个位置标记在离子页面中显示地图时效果很好。现在我想在同一张地图中添加多个标记。请在这方面帮助我。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 2020-01-19
  • 2018-02-16
  • 2013-04-21
相关资源
最近更新 更多