如何在 Angular 5 中连接 yandex 地图?我试图制作一个组件。但是在浏览器中使用会报错ng --open
:ERROR TypeError: Cannot read property 'ready' of undefined
显然没有初始化ymaps
如何加载呢?
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-yamaps',
templateUrl: './yamaps.component.html',
styleUrls: ['./yamaps.component.css']
})
export class YamapsComponent implements OnInit {
ymaps: any;
myCoordinates: any;
myMap: any;
myPlacemark: any;
closeMapButton: any;
constructor() { }
ngOnInit() {
this.ymaps.ready().then(
() => {
this.myMap = new this.ymaps.Map("map", {
center: [37.5468326405449, 55.6623162095321],
zoom: 15,
controls: ['fullscreenControl', 'geolocationControl']
}, {
yandexMapDisablePoiInteractivity: true,
suppressMapOpenBlock: true
});
//Создаем кнопку на карте
this.closeMapButton = new this.ymaps.control.Button({
data: {
content: "Закрыть карту"
},
options: {
maxWidth: [170, 400, 600]
}
});
// Задает кнопку кликом
this.myMap.events.add('click', function (e) {
if (this.myPlacemark == null)
this.myPlacemark = new this.ymaps.Placemark([], {});
this.myMap.geoObjects.add(this.myPlacemark);
var position = e.get('coords');
this.myPlacemark.geometry.setCoordinates(position);
this.myCoordinates = this.myPlacemark.geometry.getCoordinates();
document.getElementById('sendDataToServer').removeAttribute("disabled");
});
this.ymaps.geolocation.get({
// Выставляем опцию для определения положения по ip
//provider: 'yandex',
// Карта автоматически отцентрируется по положению пользователя.
mapStateAutoApply: true
}).then(function (result) {
this.myMap.geoObjects.add(result.geoObjects);
this.myPostition = result.geoObjects.position;
});
});
}
}
Stackblitz示例
这里有几个主要文件。在下载地图的服务中,您可以而且应该添加对地图是否存在的检查,以便返回已经完成的地图(如果有)。
安装了这个东西https://www.npmjs.com/package/ymaps并注册它
(window as any).global = window;
似乎工作。