ptortyr45
ptortyr45

Reputation: 147

How to embed a Yandex map in Angular?

I have a Yandex map widget and I want to embed it in an Angular component. I am using 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. Also I am not seeing any errors in the console output.

Upvotes: 4

Views: 1875

Answers (1)

Khasan 24-7
Khasan 24-7

Reputation: 467

In order to embed Yandex map on angular component, I did following steps:

  1. Added following script in main index.html(link to yandex maps api may differ by version):

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

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

Upvotes: 2

Related Questions