简体   繁体   English

如何在 Angular 中嵌入 Yandex 地图?

[英]How to embed a Yandex map in Angular?

I have a Yandex map widget and I want to embed it in an Angular component.我有一个 Yandex 地图小部件,我想将它嵌入到 Angular 组件中。 I am using Angular(v6)我正在使用 Angular(v6)

I tried to embed scripts and the root element in a tree:我试图在树中嵌入脚本和根元素:

ngAfterViewInit() {
  this.renderMapWidget();
}

renderMapWidget() {
  const ymapsScript = document.createElement('script');
  ymapsScript.src = '//api-maps.yandex.ru/2.1/?load=package.standard&lang=ru_RU';

  const ymapsWidgetScript = document.createElement('script');
  ymapsWidgetScript.src = '//...............';

  setTimeout(() => {
    document.body.appendChild(ymapsScript);
    document.body.appendChild(ymapsWidgetScript);
  }, 2000);
}

template:模板:

<div id="widget-container"></div>

Inspecting the widget in Chrome shows that the widgets root element is displayed, but the element is empty.在 Chrome 中检查小部件显示小部件根元素已显示,但该元素为空。 Also I am not seeing any errors in the console output.此外,我在控制台输出中没有看到任何错误。

In order to embed Yandex map on angular component, I did following steps:为了在角度组件上嵌入 Yandex 地图,我执行了以下步骤:

  1. Added following script in main index.html(link to yandex maps api may differ by version):在主 index.html 中添加了以下脚本(链接到 yandex maps api 可能因版本而异):

     <script src="https://api-maps.yandex.ru/2.1/?apikey=YOUR_YANDEX_API_KEY&lang=en_US" type="text/javascript"></script>
  2. The component where I wanted to embed the map:我想嵌入地图的组件:

     import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {AdBoardAddDialogService} from "app/home/ad-board-add-dialog.service"; declare const ymaps: any; @Component({ selector: 'jhi-home', templateUrl: './yandex-maps.component.html', styleUrls: ['home.scss'], }) export class YandexMapsComponent implements OnInit { map: any; latitude = 41.3; longitude = 69.3; @ViewChild('yamaps') el!: ElementRef; constructor(private adBoardAddDialogService: AdBoardAddDialogService) { } ngOnInit(): void { ymaps.ready().done(() => this.createMap()); } private createMap(): void { this.map = new ymaps.Map('map', { center: [this.latitude, this.longitude], zoom: 14 }); const placeMark = new ymaps.Placemark([this.latitude, this.longitude]); this.map.geoObjects.add(placeMark); } }
  3. And here is my yandex-maps.component.html:这是我的 yandex-maps.component.html:

     <div class="row"> <div class="col-md-12"> <div id="map" style="width: 100%; height: 600px" #yamaps> </div> </div> </div>

One can change size of the map given in html code.可以更改 html 代码中给出的地图的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM