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.
In order to embed Yandex map on angular component, I did following steps:
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>
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);
  }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With