Code Monkey home page Code Monkey logo

angular8-yandex-maps's Introduction

Angular8-yandex-maps

Yandex.Maps Angular components that implement the Yandex.Maps JavaScript API

NPM version NPM downloads Codecov

Installation

npm install angular8-yandex-maps

Version compatibility

Angular version Library version
v16, v17 v17.x
v15 v15.x
v14 v14.x
v9, v10, v11, v12, v13 v13.x
v8 v8.x
v7 v7.x
v6 v6.x
npm install angular8-yandex-maps@^8.0.0

Usage

component.html

<div class="container">
  <ya-map [center]="[55.751952, 37.600739]" [zoom]="12">
    <ya-placemark [geometry]="[55.751952, 37.600739]"></ya-placemark>
  </ya-map>
</div>

component.css

.container {
  width: 1000px;
  height: 500px;
}

SCAM

app.module.ts

Default map config options
import { AngularYandexMapsModule } from 'angular8-yandex-maps';

@NgModule({
  imports: [AngularYandexMapsModule],
})
export class AppModule {}
Own map config options
import { AngularYandexMapsModule, YaConfig } from 'angular8-yandex-maps';

const mapConfig: YaConfig = {
  apikey: 'API_KEY',
  lang: 'en_US',
};

@NgModule({
  imports: [AngularYandexMapsModule.forRoot(mapConfig)],
})
export class AppModule {}

Standalone

Default map config options
import { AngularYandexMapsModule } from 'angular8-yandex-maps';

@Component({
  selector: 'app-component',
  standalone: true,
  imports: [AngularYandexMapsModule],
})
export class Component {}
Own map config options

app.config.ts

import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { YaConfig, AngularYandexMapsModule } from 'angular8-yandex-maps';

const mapConfig: YaConfig = {
  apikey: 'API_KEY',
  lang: 'en_US',
};

export const appConfig: ApplicationConfig = {
  providers: [importProvidersFrom(AngularYandexMapsModule.forRoot(mapConfig))],
};

angular8-yandex-maps's People

Contributors

alexander-kiriliuk avatar ddubrava avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

angular8-yandex-maps's Issues

Автоматическое открытие balloon при добавлении GeoObject

Добрый день!

Angular CLI: 11.2.3
Node: 12.13.0
OS: darwin x64

Angular: 11.2.4

"angular8-yandex-maps": "11.0.1"

Я добавляю GeoObject на карту по щелчку, с помощью *ngFor

<ya-map [center]=[55.76,37.64] (yaclick)="yaMapClick($event)"> <ya-geoobject *ngFor="let point of yaPoints" [feature]="point.feature" [options]="point.options"></ya-geoobject> </ya-map>

Для каждой точки я задаю содержимое balloon и мне нужно чтобы он сразу открывался

получилось навесить на каждый геообъект ya событие мыши
<ya-map [center]=[55.76,37.64] (yaclick)="yaMapClick($event)"> <ya-geoobject *ngFor="let point of yaPoints" [feature]="point.feature" (yamouseleave)="openBaloon($event)" [options]="point.options"></ya-geoobject> </ya-map>
тогда при наведении мыши на объект balloon открывается нормально
openBaloon(event: YaEvent) { event.target.balloon.open(); }

упорно не понимаю как вызвать метод balloon.open() автоматически при создании объекта

так же не получается просто открыть любой balloon с помощью
const yaMap=event.ymaps.Balloon.prototype.open([55.76,37.64],'Example balloon');
Ошибка
ERROR TypeError: Cannot read property 'set' of undefined

Локальная ошибка запроса геокодера

🐞 Bug Report

✍️ Description

Геокодер не передаёт ключ при выполнении запроса.

🔬 Reproduction

Для примера возьмём вот этот же стакблитз

При вводе символа в поле ввода над картой отправляется такой запрос
image

При локальном, таком же запросе, апи-ключ куда-то теряется, хотя сама карта инициализируется и корректно работает, в том числе с прочими функциями.

image

подключение в модуле, компоненты которого используют апи карт
image

модуль в приложении подключен через ленивую загрузку
image

🌎 Environment

Angular CLI: 11.2.2
Node: 12.0.0
OS: win32 x64

Angular: 11.2.3
... animations, common, compiler, compiler-cli, core, forms
... language-service, localize, platform-browser
... platform-browser-dynamic, router
Ivy Workspace: Yes

Package Version

@angular-devkit/architect 0.1102.2
@angular-devkit/build-angular 0.1102.2
@angular-devkit/core 11.2.2
@angular-devkit/schematics 11.2.2
@angular/cli 11.2.2
@schematics/angular 11.2.2
@schematics/update 0.1102.2
rxjs 6.6.6
typescript 4.1.5

angular8-yandex-maps ^11.0.1

Null Inject Error

I get this errors:
StaticInjectorError(RootModule)[API_KEY]:
StaticInjectorError(Platform: core)[API_KEY]:
NullInjectorError: No provider for API_KEY!

Cannot read property 'initScript' of undefined
at YandexMapComponent.push../node_modules/angular8-yandex-maps/fesm5/angular8-yandex-maps.js.YandexMapComponent.ngOnInit (angular8-yandex-maps.js:472)

My module import:
AngularYandexMapsModule.forRoot('my-key-xxx'),

Как обратиться к геокодеру напрямую?

❓ Help Wanted

✍️ Description

Подключил карту в компоненте инстансом скрипта через подписку

this.yaScriptService.initScript().subscribe((ymaps) => {
 тут создал карту и геометку, всё ок
}));

но вот как обратиться к yamaps.geocode("Москва") из примеров и документации так и не понял. Реквестую помощь

🌎 Environment

Angular CLI: 11.2.2
Node: 12.0.0
OS: win32 x64

Angular: 11.2.3
... animations, common, compiler, compiler-cli, core, forms
... language-service, localize, platform-browser
... platform-browser-dynamic, router
Ivy Workspace: Yes

Package Version

@angular-devkit/architect 0.1102.2
@angular-devkit/build-angular 0.1102.2
@angular-devkit/core 11.2.2
@angular-devkit/schematics 11.2.2
@angular/cli 11.2.2
@schematics/angular 11.2.2
@schematics/update 0.1102.2
rxjs 6.6.6
typescript 4.1.5

angular8-yandex-maps версии пробовал и ^11.0.1 и ^10.3.1 как в примере тут

В опциях ymaps.Placemark отсутствует свойство balloonCloseButton

🐞 Bug Report

✍️ Description

В опциях ymaps.Placemark отсутствует свойство balloonCloseButton

🔬 Reproduction

1 Берем первый пример по ссылке https://yandex.ru/dev/maps/jsapi/doc/2.1/ref/reference/Placemark.html
2. Пробуем воспроизвести его с помощью компонента ya-placemark.
3 Получаем ошибку при загрузке карты..

🌎 Environment

Angular version: 12.1.2
angular8-yandex-maps version:12.1.7

Есть ли возможность работы с SuggestView

Использую последнюю версию модуля. Необходимо реализовать обычный SuggestView, который в проекте без Angular реализуется за 2 минуты. Собственно вопрос, есть ли возможность используя ваш модуль организовать SuggestView?

bootstrap-4 портит отображение карты

Здравствуете.
Я новичок в angular и недавно начал использовать данное решение в своем проекте. У меня возникла ошибка с отображением карты из-за bootstrap-4. Его классы .container дополнительно накладывается на тот класс что используется в решении (bootstrap устанавливал по этой инструкции https://loiane.com/2017/08/how-to-add-bootstrap-to-an-angular-cli-project/).
Ну и мой вопрос, как быть дальше:

  1. Отключать bootstrap (не вариант)?
  2. Есть какие-то предложения как мне решить данную проблему?

No icon caption?

In the examples there are hintContent and balloonContent, but I didn't find iconCaption, which will be displayed initially independently on hover or click as hintContent and balloonContent. Does this option exist in this project?

Broken depedencies

🐞 Bug Report

Couldn't install library on current angular version

✍️ Description

Couldn't install library on Angular 12.1.0

🔬 Reproduction

  1. Setup new minimal Angular progect.
  2. Run npm i angular8-yandex-maps in project directory

🌎 Environment

Angular 12.1.3

angular8-yandex-maps
2021-07-25T05_49_52_698Z-debug.log
eresolve-report.txt
12.1.5

Issues with angular ^10 and ya-maps ^10

Describe the bug
After update from angular 9 to angular 10.2.0, and ya-map from 1.12.0 to 10.4.0 i have some execptions.

`
ERROR in node_modules/angular8-yandex-maps/lib/models/models.d.ts:45:19 - error TS2686: 'ymaps' refers to a UMD global, but the current file is a module. Consider adding an import instead.

45 ymaps: typeof ymaps;
~~~~~
node_modules/angular8-yandex-maps/lib/models/models.d.ts:55:19 - error TS2686: 'ymaps' refers to a UMD global, but the current file is a module. Consider adding an import instead.

55 ymaps: typeof ymaps;
~~~~~
node_modules/angular8-yandex-maps/lib/services/script/script.service.d.ts:19:45 - error TS2686: 'ymaps' refers to a UMD global, but the current file is a module. Consider adding an import instead.

19 initScript(): Observable<Event | typeof ymaps>;
`

Package version
`
@angular-devkit/architect 0.1002.0

@angular-devkit/build-angular 0.1002.0

@angular-devkit/core 10.2.0

@angular-devkit/schematics 10.2.0

@angular/cli 10.2.0

@schematics/angular 10.2.0

@schematics/update 0.1002.0

rxjs 6.5.5

typescript 4.0.5

`

Additional context
`
{
"name": "orda-satu-new",

"version": "0.0.0",

"scripts": {

"ng": "ng", 

"start": "ng serve",

"build": "ng build",

"test": "ng test",

"lint": "ng lint",

"e2e": "ng e2e"

},

"private": true,

"dependencies": {

"@angular/animations": "~10.2.2",

"@angular/common": "~10.2.2",

"@angular/compiler": "~10.2.2",

"@angular/core": "~10.2.2",

"@angular/forms": "~10.2.2",

"@angular/platform-browser": "~10.2.2",

"@angular/platform-browser-dynamic": "~10.2.2",

"@angular/router": "~10.2.2",

"@fancyapps/fancybox": "^3.5.7",

"@fortawesome/angular-fontawesome": "^0.7.0",

"@fortawesome/fontawesome-svg-core": "^1.2.30",

"@fortawesome/free-brands-svg-icons": "^5.14.0",

"@fortawesome/free-solid-svg-icons": "^5.14.0",

"@ng-bootstrap/ng-bootstrap": "^6.1.0",

"@ngx-translate/core": "^12.1.2",

"@ngx-translate/http-loader": "^4.0.0",

"angular8-yandex-maps": "^10.4.0",

"animate.css": "^3.7.2",

"bootstrap": "^4.4.1",

"ion-rangeslider": "^2.3.1",

"jquery": "^3.5.1",

"moment": "^2.25.1",

"ng-bootstrap": "^1.6.3",

"ng-image-slider": "^2.6.4",

"ng-pdf-make": "^0.1.1",

"ng2-ion-range-slider": "^2.0.0",

"ngx-clipboard": "^13.0.1",

"ngx-device-detector": "^1.4.5",

"ngx-google-analytics": "^9.0.0",

"ngx-image-zoom": "^0.6.0",

"ngx-instabuy-utils": "0.0.5",

"ngx-mask": "^9.0.2",

"ngx-owl-carousel": "^2.0.7",

"ngx-owl-carousel-o": "^3.0.0",

"ngx-pipes": "^2.7.3",

"ngx-sharebuttons": "^8.0.0",

"owl-carousel": "^1.0.0",

"owl.carousel": "^2.3.4",

"rxjs": "~6.5.4",

"script-loader": "^0.7.2",

"tslib": "^2.0.0",

"using-custom-elements": "^1.0.0",

"zone.js": "~0.10.2"

},

"devDependencies": {

"@angular-devkit/build-angular": "~0.1002.0",

"@angular/cli": "^10.2.0",

"@angular/compiler-cli": "~10.2.2",

"@angular/language-service": "~10.2.2",

"@types/jasmine": "~3.5.0",

"@types/jasminewd2": "~2.0.3",

"@types/jquery": "^3.3.38",

"@types/node": "^12.11.1",

"@types/yandex-maps": "^2.1.13",

"codelyzer": "^5.1.2",

"jasmine-core": "~3.5.0",

"jasmine-spec-reporter": "~5.0.0",

"karma": "~5.0.0",

"karma-chrome-launcher": "~3.1.0",

"karma-coverage-istanbul-reporter": "~3.0.2",

"karma-jasmine": "~4.0.0",

"karma-jasmine-html-reporter": "^1.5.0",

"protractor": "~7.0.0",

"ts-node": "~8.3.0",

"tslint": "~6.1.0",

"typescript": "~4.0.5"

}
}
`

Не удается получить адресс из поля

Получил instance из angular-yandex-map и добавил SuggestView. Все прекрастно работает до того момента пока не попытаешь из этого поля взять адресс. Вместо полного адресса я получаю только то, что я написал сам, а не полностью весь адресс.

Создаю SuggestView

public onLoad(event: ILoadEvent) {
   const ymaps = event.ymaps;

   ymaps.load().then(res => {
     var suggest = new res.SuggestView('training_address');
   }).catch(error => console.log(error));
}

HTML:

        <div class="map">
          <angular-yandex-map [onlyInstance]="true" (load)="onLoad($event)"></angular-yandex-map>
        </div>
        <input name="address" [(ngModel)]="address" type="text" id="training_address"
                                          class="form-control"
                                          nbInput fullWidth status="basic"
                                          placeholder="Kirjutage treeningute addressi...">

В чем может быть проблема?

Не обновляется состояние карты

Добрый день! У меня тоже не обновляется состояние карты, но кейс немного другой. Без разницы есть ли кластеризация или нет. Ошибки в консоль не сыпятся, но визуальное обновление списка отметок происходит только когда я нажимаю что-либо на клавиатуре.

До актуальной версии (10.2.0) обновился.

upd: вызов любой функции компонента (в том числе через setInterval) тоже запускает перерисовку карты. Почему может без этого не отрабатывать?

Originally posted by @tonghae in #32 (comment)

Карта не работает в firefox 45 версии

Здравствуйте. На сколько я помню версия 1.12.0 работала firefox 45
После перехода на 1.14.5, карта перестала отображаться, ошибок никаких нет, просто пустой компонент angular-yandex-map
Версия карты подключается 2.1
Судя по документации https://tech.yandex.ru/maps/jsapi/doc/2.1/dg/concepts/load-docpage/ для старых браузеров IE8, IE9 и IE10 автоматически должна подгружаться другая версия 2.1.oldie.1
Возможно то же касается и firefox 45

Error: getInternalNameOfClass() called on a non-ES5 class

Ошибка при сборке

версия angular8-yandex-maps 11.0.2

[ERROR] Warning: Invalid constructor parameter decorator in E:/.../frontend/node_modules/angular8-yandex-maps/fesm2015/angular8-yandex-maps.js:
[ERROR] () => [
[ERROR] { type: NgZone }
[ERROR] ]
[ERROR] Error: Error on worker #1: Error: getInternalNameOfClass() called on a non-ES5 class: expected YaGeoObjectComponent to have an inner class declaration
[ERROR] at Esm5ReflectionHost.getInternalNameOfClass (E:...\frontend\node_modules@angular\compiler-cli\ngcc\src\host\esm5_host.js:88:23)
[ERROR] at DelegatingReflectionHost.getInternalNameOfClass (E:...\frontend\node_modules@angular\compiler-cli\ngcc\src\host\delegating_host.js:89:34)
[ERROR] at Object.extractDirectiveMetadata (E:...\frontend\node_modules@angular\compiler-cli\src\ngtsc\annotations\src\directive.js:237:69)
[ERROR] at ComponentDecoratorHandler.analyze (E:...\frontend\node_modules@angular\compiler-cli\src\ngtsc\annotations\src\component.js:143:47)
[ERROR] at NgccTraitCompiler.TraitCompiler.analyzeTrait (E:...\frontend\node_modules@angular\compiler-cli\src\ngtsc\transform\src\compilation.js:345:40)
[ERROR] at analyze (E:...\frontend\node_modules@angular\compiler-cli\src\ngtsc\transform\src\compilation.js:297:58)
[ERROR] at _loop_1 (E:...\frontend\node_modules@angular\compiler-cli\src\ngtsc\transform\src\compilation.js:319:21)
[ERROR] at NgccTraitCompiler.TraitCompiler.analyzeClass (E:...\frontend\node_modules@angular\compiler-cli\src\ngtsc\transform\src\compilation.js:325:35)
[ERROR] at NgccTraitCompiler.analyzeFile (E:...\frontend\node_modules@angular\compiler-cli\ngcc\src\analysis\ngcc_trait_compiler.js:47:26)
[ERROR] at DecorationAnalyzer.analyzeProgram (E:...\frontend\node_modules@angular\compiler-cli\ngcc\src\analysis\decoration_analyzer.js:134:39)
[ERROR] at ClusterMaster.onWorkerMessage (E:...\frontend\node_modules@angular\compiler-cli\ngcc\src\execution\cluster\master.js:194:27)
[ERROR] at E:...\frontend\node_modules@angular\compiler-cli\ngcc\src\execution\cluster\master.js:54:95
[ERROR] at ClusterMaster. (E:...\frontend\node_modules@angular\compiler-cli\ngcc\src\execution\cluster\master.js:292:57)
[ERROR] at step (E:...\frontend\node_modules\tslib\tslib.js:141:27)
[ERROR] at Object.next (E:...\frontend\node_modules\tslib\tslib.js:122:57)
[ERROR] at E:...\frontend\node_modules\tslib\tslib.js:115:75
[ERROR] at new Promise ()
[ERROR] at Object.__awaiter (E:...\frontend\node_modules\tslib\tslib.js:111:16)
[ERROR] at EventEmitter. (E:...\frontend\node_modules@angular\compiler-cli\ngcc\src\execution\cluster\master.js:286:32)
[ERROR] at EventEmitter.emit (events.js:315:20)
[ERROR] An unhandled exception occurred: NGCC failed.
[ERROR] See "C:...\angular-errors.log" for further details.
[ERROR] npm ERR! file C:\Windows\system32\cmd.exe
[ERROR] npm ERR! code ELIFECYCLE
[ERROR] npm ERR! errno ENOENT
[ERROR] npm ERR! syscall spawn
[ERROR] npm ERR! [email protected] build-prod: node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build --prod
[ERROR] npm ERR! spawn ENOENT
[ERROR] npm ERR!
[ERROR] npm ERR! Failed at the [email protected] build-prod script.
[ERROR] npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

(если в package.json дописать "postinstall": "ngcc", то ошибка пропадает)

Кастомный iconContent

Подскажите пожалуйста как в вашей библиотеке можно сделать свой кастомный iconContent?
Если обратиться к оф. документации мы видим следующее https://tech.yandex.ru/maps/jsbox/2.1/?from=techmapsmain

Где iconContentLayout: MyIconContentLayout, а MyIconContentLayout в свою очередь создается следующим образом (более наглядно по ссылке):

MyIconContentLayout = ymaps.templateLayoutFactory.createClass(
'

$[properties.iconContent]
'
),

Подскажите как в данной библиотеке это реализовать?

Cоздание собственной карты

Здравствуйте.
Можно ли создать собственную карту?
Пример https://yandex.ru/dev/maps/jsbox/2.1/custom_map/

При попытке перенять код из api yandex остановился на пункте:

// Задаем в качестве проекции Декартову. При данном расчёте центр изображения будет лежать в координатах [0, 0].
projection: new ymaps.projection.Cartesian([[PIC_HEIGHT / 2 - worldSize, -PIC_WIDTH / 2], [PIC_HEIGHT / 2, worldSize - PIC_WIDTH / 2]], [false, false])

метод карты setBounds()

Есть ли у карты метод setBounds()?
Задача центрировать карту и установить подходящий зум, чтобы были видны все метки.

angular8-yandex-maps v1.14.3

Ошибка при дестрое объекта карты

Здравствуйте! Ранее заводила проблему, связанную с ошибкой "Cannot read property 'geoObjects' of undefined" при использовании кластера (#32). Сейчас сталкиваюсь в похожей проблемой, кейс подобный, но немного отличается.
Есть несколько табов на странице - на каждом разный контент, при определенных условиях таб при инициализации меняется автоматически. На первом табе присутствует компонент карты и в случае, если карта еще не успела полностью отрисоваться, а таб переключается, в консоли падают ошибки Cannot read property 'geoObjects' of undefined и Cannot read property 'offsetWidth' of null, что крашит приложение. Также воспроизводится, если попытаться быстро переключить таб и вручную, есть вероятность, что карта все же не будет прогружена полностью.
При дебаге кидает на строку кода на скрине (Cannot read property 'geoObjects' of undefined)
image
Cannot read property 'offsetWidth' of null генерится методом getSize

Пример - https://stackblitz.com/edit/ya-clusterer-tabs?file=src/app/map-container/map-container.component.ts

Начали ловить ошибку с версией библиотеки ^10.2.0.
Обновилась до версии ^10.4.0, дабы проверить сохраняется ли ошибка, но столкнулась со второй проблемой - не собирается проект с ошибками 'ymaps' refers to a UMD global, but the current file is a m
odule. Consider adding an import instead. (@types/yandex-maps установлен, верисия ^2.1.13). Подскажите, с чем это может быть связано?

The namespace ymaps was declared in non-npm package.

Добрый день. Я некоторое время искал причину, по которой у меня не видно пространства имен ymaps при использовании angular8-yandex-maps. Я делал по примеру: https://stackblitz.com/edit/placemark?file=node_modules%2Fangular8-yandex-maps%2Flib%2Ftypings%2Fyandex-maps%2Findex.d.ts. И когда, при поиске решения, догадался в этом примере отыскать где-же определено это пространство имен, то обнаружил, что оно находится в index.d.ts. Я в angular новичок. Но как мне кажется, его не видно в моем проекте из-за того что оно было объявлено в .d.ts. И там-же, в этом же файле как-раз в оглавлении и написано: "Type definitions for non-npm package yandex-maps 2.1."

метка default#imageWithContent

Добрый день, в примере https://stackblitz.com/edit/custom-placemark я добавляю у метки обработчик события yaclick и все работает.
Но если у метки поменять iconLayout на 'default#imageWithContent', то событие не работает. Как можно это исправить?

setCenter dynamically

How to set center dynamically?
I tried this - https://stackblitz.com/edit/map-set-center-async?file=angular.json, but i got error - contacts.component.html:35 ERROR TypeError.

Help me please.)

update:

<div class="project-map"> <angular-yandex-map [center]="center" [zoom]="12"> <angular-yandex-placemark *ngFor="let item of contactsMap" [geometry]="item?.geometry" [properties]="item?.properties" (load)="onLoad($event)" [options]="item?.options"></angular-yandex-placemark> </angular-yandex-map> </div>

`import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { OtherService } from '../../shared/services/other.service';
import { ILoadEvent } from 'angular8-yandex-maps';

@component({
selector: 'app-contacts',
templateUrl: './contacts.component.html',
styleUrls: ['./contacts.component.scss']
})
export class ContactsComponent implements OnInit {

contacts: any[];
selected: any;
contactsMap = [];
center = [];

constructor(private otherService: OtherService, private _changeDetectorRef: ChangeDetectorRef) { }

ngOnInit(): void {
this.center = [51.128207, 71.430411];
this.otherService.getContacts()
.then(res => {
this.contacts = (res as any);
this.selected = this.contacts[0];
this.contactsMap.push(this.selected);
})
}

getCoords(item) {
if (item.lat && item.lng) {
return [item.lat.toString(), item.lng.toString()];
}
else {
return null;
}
}

selectContact(item) {
this.selected = item;
this.contactsMap = [];
this.contactsMap.push(this.selected);
this._changeDetectorRef.detectChanges();
this.setCenter(item.geometry);
}

getPlacemarksProperties(item) {
return {
hintContent: item.name,
balloonContent: item.address
}
}

public onLoad(event: ILoadEvent) {
//this.map = event.instance;
}

public setCenter(coords: any[]): void {
this.center = coords;
//this.map.setCenter(coords);

}

}`

При первой загрузке карты координаты перепутаны местами

❓ Help Wanted

✍️ Description

При первой загрузке приложения либо через жесткую перезагрузку со сбросом кэша метки на карте отображаются так
image
после обычной перезагрузки страницы метки отображаются корректно
image
Судя по всему почему-то путаются lat и lon

🌎 Environment

Angular CLI: 9.0.7
Node: 12.19.0
OS: win32 x64

Angular: 9.1.13
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, upgrade
Ivy Workspace: Yes

Package Version

@angular-devkit/architect 0.900.7
@angular-devkit/build-angular 0.900.7
@angular-devkit/build-optimizer 0.900.7
@angular-devkit/build-webpack 0.900.7
@angular-devkit/core 7.3.10
@angular-devkit/schematics 7.3.10
@angular/cdk 9.2.4
@angular/cli 9.0.7
@angular/language-service 9.0.7
@angular/material 9.2.4
@angular/router 9.0.7
@ngtools/webpack 9.0.7
@schematics/angular 9.0.7
@schematics/update 0.900.7
rxjs 6.5.5
typescript 3.7.5
webpack 4.41.2

"angular8-yandex-maps": "^9.0.0",

как задавать метке preset?

❓ Изменение метки

✍️ Пытаюсь на уже отрисованной карте с метками изменять свойство preset.

options: {
    preset: "islands#yellowStretchyIcon"
}

Присваивая ключу новое значение, никаких изменений не происходит.
Получается добавлять или удалять метки на карте, добавляя в существующий массив данных новый элемент, или удаляя его.

Вкратце. Есть компонент с картой, и есть компонент со списком местоположений. Я из списка местоположений передаю индекс элемента и тип события в компонент карты при наведении на элемент из компонента списка местоположений. Хочу добиться похожего эффекта, как на https://www.airbnb.ru/

метод (ready) GeoObject срабатывает не всегда, ждет отрисовки карты

🌎 Environment

Angular CLI: 11.2.3
Node: 12.13.0
OS: darwin x64

Angular: 11.2.4

"angular8-yandex-maps": "11.0.2"

✍️ Description

Добрый день! задавал вопрос [#72] по поводу автоматического открывания ballon, теперь использую метод (ready) геообъекта.
Нашел проблему с его работой. Если вкратце: Навесил на событие resultshow объекта searchControl добавление новой точки. Иногда оно срабатывает, иногда нет, помогает только изменение размера окна или зума на карте.
Добавление новой точки по клику на карте отрабатывает всегда.

Если отключить событие геообъекта (ready) - точки всегда добавляются и через поиск и через клик на карте.

Пример кода create-geoobject-onsearch-result

When i use angular universal i get this error

TypeError: Cannot read property 'geoObjects' of undefined
at YaPlacemarkComponent.../node_modules/angular8-yandex-maps/ivy_ngcc/bundles/angular8-yandex-maps.umd.js.YaPlacemarkComponent.ngOnDestroy (E:\Shop-online\dist\viewer\server\main.js:171213:23)
at executeOnDestroys (E:\Shop-online\dist\viewer\server\main.js:75718:32)
at cleanUpView (E:\Shop-online\dist\viewer\server\main.js:75640:13)
at destroyViewTree (E:\Shop-online\dist\viewer\server\main.js:75435:51)
at destroyLView (E:\Shop-online\dist\viewer\server\main.js:75593:13)
at RootViewRef.../node_modules/@angular/core/ivy_ngcc/bundles/core.umd.js.ViewRef.destroy (E:\Shop-online\dist\viewer\server\main.js:76335:13)
at E:\Shop-online\dist\viewer\server\main.js:95296:71
at Array.forEach ()
at ApplicationRef.../node_modules/@angular/core/ivy_ngcc/bundles/core.umd.js.ApplicationRef.ngOnDestroy (E:\Shop-online\dist\viewer\server\main.js:95296:33)

конфигурация не применяется, когда карта подключается не в главном модуле приложения

Описание:
конфигурация не применяется, когда карта подключается не в главном модуле приложения

Воспроизведение:
карта находится в отдельном модуле (map.module.ts), подключена вот так:
AngularYandexMapsModule.forRoot({ apiKey: 'my-key', lang: 'ru_RU'})
После запуска приложения указанная конфигурация не применяется (ключ становится null и локализация en_RU), хотя карта работает.

Ожидание:
angular-yandex-maps подключен только в модуле map.module.ts, применяется указанная конфигурация.

Версия: 1.14.0

Дополнительно:
конфигурация срабатывает только если прописать в главном модуле приложения (app.module.ts)
AngularYandexMapsModule.forRoot({ apiKey: 'my-key', lang: 'ru_RU'})

Получаю ошибку ExpressionChangedAfterItHasBeenCheckedError

Describe the problem
Добрый день.

Не могу понять проблема у меня или в библиотеке?

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'center: 50.78455100000636,36.48868599999999'. Current value: 'center: 53.35900409942692,37.10592749999995'.

Шаблон:

<ya-map *ngIf="addressesCoordinatesMap.size" [center]="center" [zoom]="zoom">
    <ng-container *ngFor="let coordinates of addressesCoordinatesMap | keyvalue">
        <ya-placemark [geometry]="coordinates.value.coordinates" [properties]="coordinates.value.properties"
                      (load)="calculateCenterAndZoom()"></ya-placemark>
    </ng-container>
</ya-map>

в calculateCenterAndZoom() пересчитывается центр и зум при добавлении новой точки, средствами this.ymaps.util.

Package version
angular8-yandex-maps: 8.1.0

Ошибка при использовании ya-clusterer

Добрый день!

Пытаюсь через ngFor вывести ya-placemark внутри ya-clusterer. При первой инциализации все хорошо отрабатывает. Вызываю роут на другой раздел приложения (в том же модуле), компонент, внутри которого карта, уничтожается без проблем, карта - тоже. Возвращаюсь к разделу с картой - при инициализации почему-то сразу вызывается ngOnDestroy у всех YaPlacemarkComponent, и при дестрое компонента-контейнера вылазит ошибка "Cannot read property 'geoObjects' of undefined", возникает она в методе ngOnDestroy YaPlacemarkComponent, т.к. там происходит обращение к _map.geoObjects, а свойство _map в этот момент является undefined.

Возможно я как-то неверно использую ya-clusterer?
image

Multiroute

❓ Help Wanted

Can't use viaIndexes to hide viaPoints with option: viaPointVisible:false;

Использование ngFor для <angular-yandex-geoobject>

При добавлении нового Point объекта, карта не меняется:

import {Component, OnInit} from '@angular/core';
import {IEvent} from "angular8-yandex-maps";

class Point {
    constructor(
        public lat: number,
        public long: number,
        public radius: number
    ) {}

    public get feature() {
        return {
            geometry: {
                type: "Circle",
                coordinates: [this.lat, this.long],
                radius: this.radius
            }
        }
    }

    public get options() {
        return {
            draggable: true
        }
    }
}


@Component({
    selector: 'home-search-comp',
    template: `
        <div id="homeSearchContainer" class="home-search-container">
            <angular-yandex-map [center]="[53.902496, 27.561481]" [zoom]="12" (yaclick)="onClick($event)">
                <angular-yandex-geoobject *ngFor="let point of points"
                                          [feature]="point.feature"
                                          [options]="point.options"
                ></angular-yandex-geoobject>
            </angular-yandex-map>
        </div>
    `,
})
export class HomeSearchComponent implements OnInit {

    public points: Point[] = []

    ngOnInit() {
        this.points.push(new Point(53.902496, 27.561481, 1000))
    }

    onClick(event:IEvent) {
        let coords = event.event.get('coords')
        this.points.push(new Point(coords[0], coords[1], 1000))
        console.log(this.points)
    }

}

Если таким образом добавление регионов не работает, то подскажите, пожалуйста, как это лучше сделать?

Placemark перемещается при скроле в Chrome\Edge и карта прогружается только когда скролишь в Mozilla

Describe the bug

  1. Placemark перемещается при скроле в Chrome\Edge
  2. Карта прогружается только когда скролишь в Mozilla

Код простой

                  <ya-map (load)="onMapLoad($event)" [center]="[]" [zoom]="16">
                    </ya-map>
  public async onMapLoad(event): Promise<any> {
    const res = await event.ymaps.geocode(this.vuz.Adress);

    // Выбираем первый результат геокодирования.
    const firstGeoObject = res.geoObjects.get(0);
    const coords = firstGeoObject.geometry.getCoordinates();

    // Масштабируем карту на область видимости геообъекта.
    event.instance.setCenter(coords);
    var placemark = new event.ymaps.Placemark(coords, {}, {
      balloonHeader: this.vuz.Name,
      balloonBody: '<img class="page_avatar_img" src="<url>' + this.vuz.Logo + '" alt="' + this.vuz.Name + '" width="100" height="100">',
      //balloonFooter: '<a href="../about" routerLinkActive="active"> Данные указаны не точно? </a>',
      draggable: false  
    });
    event.instance.geoObjects.add(placemark);
  }

To Reproduce
Steps to reproduce the behavior:

  1. Используйте загрузку карты с меткой + масштабирование как у меня
  2. Открыть браузеры указанные выше

Expected behavior
Думаю тут комментарии лишние

Screenshots
map

Package version
10.0.0

Unable to get SuggestView from ymaps

❓ Help Wanted

Please give me a hint, where is my mistake?

Using this sample and using new service (YaApiLoaderService), getting error TS2339: Property 'SuggestView' does not exist on type 'typeof ymaps'.

Here is the code:

ngOnInit(): void {
this.yaApiLoaderService.load().subscribe(ymaps => {
const suggest = new ymaps.SuggestView('suggest');
suggest.events.add(['select'], e => console.log(e));
console.log(ymaps);
});
}

console.log(ymaps); -> shows SuggestView as well.

"angular8-yandex-maps": "^12.1.4",
@angular-devkit/architect 0.1102.13
@angular-devkit/build-angular 0.1102.13
@angular-devkit/core 11.2.13
@angular-devkit/schematics 11.2.13
@angular/cli 11.2.13
@schematics/angular 11.2.13
@schematics/update 0.1102.13
rxjs 6.6.7
typescript 4.1.5

Unable to set ya-placemark options. Type error.

Describe the bug
Passing [options]="placemarkOptions" input to the ya-placemark component gives Type '{ iconLayout: string; iconImageHref: string; iconImageSize: number[]; }' has no properties in common with type 'IPlacemarkOptions'.

To Reproduce
Steps to reproduce the behavior:

  1. Clone this example.
  2. Run.
  3. See error in terminal.

Expected behavior
Placemark icon should be changed without errors.

Package version
"angular8-yandex-maps": "^10.4.1"
"@angular/core": "~10.2.2"

BTW, In the example mentioned the placemark shifts it's position drastically when zooming.

Координаты клика

❓ Help Wanted

Доброго времени суток! Перекопал кучу документации, но так и не понял, как мне получить координаты клика по карте?

Через (yaclick)="setPoint($event)" не нашел переменной с координатами или метода, их возвращающего.

Заранее благодарен!

Как задать параметеры objectManager'у?

Не нашел в документации и в примерах, как можно задать параметры для objectManager'а, например geoObjectOpenBalloonOnClick. И как через него в коде можно добавить объекты.

How to extract ymaps instance?

Describe the problem
In the description you are writing: "It also returns ymaps instance so you can use full API." How can I get access to it?

Получаю Invalid Api Key даже без его указания

Module:
import {AngularYandexMapsModule} from 'angular8-yandex-maps';
import:[AngularYandexMapsModule]

Component.ts:

constructor() {}
public onLoad(event: ILoadEvent) {
const ymaps = event.ymaps;

ymaps.geocode('Moscow')
  .then((res) => {
    console.log(
      res.geoObjects.get(0).properties.get('metaDataProperty')
    );
  });
 }

Component.html:
<div class="map"> <angular-yandex-map [onlyInstance]="true" (load)="onLoad($event)"></angular-yandex-map> </div>

Получаю: Invalid Api Key, соответсвенно ничего не выводится

Замена @Component на @Directive, там где не используются html шаблоны

Feature request

Предлагаю заменить @Component на @Directive, потому что данные компоненты не имеют шаблонов (кроме ya-map и ya-panorama).
КМК это более правильное решение.
При этом решении, можно будет убрать не нужные html и scss файлы - станет чище

Пример: Google map в @angular/components
https://github.com/angular/components/blob/master/src/google-maps/map-bicycling-layer/map-bicycling-layer.ts#L21-L24

Нужно получение адреса маркера который поставил пользователь через поиск

Здравствуй, можешь пожалуйста подсказать каким образом можно получить адрес который указал пользователь? Ну или как написать event на новый маркер на карте (Когда пользователь пишет нужный адрес появляется маркер).Буду очень благодарен

Возможно ли создание метки с собственным изображением и с подписью (caption метки)?

т.к. нужно обрабатывать событие клика на метку и подпись к ней.

если в примере https://stackblitz.com/edit/custom-placemark
добавить iconCaption, то подпись не показывается

public placemarkProperties = {
    iconCaption: '3333333',
    hintContent: 'Hint content',
    balloonContent: 'Baloon content',
  }

если реализовать с помощью default#imageWithContent (метка, а рядом с ней iconContent), то не получается сменить курсор над iconContent и добавить к нему клик. длина iconContent меняется

public onLoad(event: ILoadEvent) {
    const myIconContentLayout = event.ymaps.templateLayoutFactory.createClass(
        '<div style="display: inline; white-space: nowrap; font-size: 1.5rem; background-color: white;">$[properties.iconContent]</div>'
    );

    this.placemarkOptions = {
      iconLayout: 'default#imageWithContent',
      iconImageHref: '../../../../assets/icons/pin.png',
      iconImageSize: [23, 33],
      iconImageOffset: [-10, -33],
      iconContentLayout: myIconContentLayout,
      iconContentOffset: [23, 5],
    };
  }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.