Home javascript Yandex maps are loaded only after clicking on the page

Yandex maps are loaded only after clicking on the page

Author

Date

Category

I use Yandex Maps API and Angular 6. When I start the Angular CLI server, the console always pops up:

MapsComponent_Host.ngfactory.js? [sm]: 1

ERROR ReferenceError:
ymaps is not defined
at MapsComponent.push ../ src / app / main-layout / main-layout / maps.component.ts.MapsComponent.ngOnInit
(maps.component.ts: 19)
at checkAndUpdateDirectiveInline (core.js: 9243)
at checkAndUpdateNodeInline (core.js: 10507)
at checkAndUpdateNode (core.js: 10469)
at debugCheckAndUpdateNode (core.js: 11102)
at debugCheckDirectivesFn (core.js: 11062)
at Object.eval [as updateDirectives] (MapsComponent_Host.ngfactory.js? [sm]: 1)
at Object.debugUpdateDirectives [as updateDirectives] (core.js: 11054)
at checkAndUpdateView (core.js: 10451)
at callViewAction (core.js: 10692)

But after I go through the routing for example to the / login component and return back, the map suddenly appears.

My index.html:

& lt;! doctype html & gt;
& lt; html lang = "en" & gt;
& lt; head & gt;
...
& lt; / head & gt;
& lt; body & gt;
& lt; / body & gt;
& lt; script src = "https://api-maps.yandex.ru/2.1/?apikey=...&lang=ru_RU" type = "text / javascript" & gt; & lt; / script & gt;
...
& lt; / html & gt;

Maps.component.html has:

& lt; div id = "map" style = "width: 600px; height: 400px" & gt; & lt; / div & gt;

maps.component.ts contains:

import {Component, OnInit} from '@ angular / core';
import {MainLayoutService} from '../main-layout.service';
declare var ymaps: any;
@Component ({
selector: 'app-dashboard',
 templateUrl: './maps.component.html'
})
export class MapsComponent implements OnInit {
 properties: object;
 public map: any;
 constructor (private service: MainLayoutService) {
 }
 ngOnInit () {
  ymaps.ready (). then (() = & gt; {
   this.map = new ymaps.Map ('map', {
    center: [50.450100, 30.523400],
    zoom: 6
   });
  });
 }
}

Answer 1, authority 100%

Put the map loading script in head so that it is fully loaded before working with the DOM. Also the error Uncaught TypeError: Cannot set property 'map' of undefined occurs due to loss of context, you need to either bind it:

ymaps.ready (). then (this.initMap.bind (this));

Or use an arrow function:

private initMap = () = & gt; {
  ...
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions