Coder Social home page Coder Social logo

vue-yandex-map's Issues

Подключение в Nuxt

По возможности, сделайте поддержку ssr, или напишите в документации, как подключить плагин в Nuxt. Если следовать алгоритму на сайте Nuxt для подключения client-side only плагинов, попадаю на ошибки разных мастей, самая безобидная из которых - сайт работает, но карта не отображается, а в консоли пишет про отличия деревьев VNode и ClientNode.

ошибка Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

inception-1519300852896.js:5 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
at Object. (VM3109 inception-1519300852896.js:5)
at Object. (VM3109 inception-1519300852896.js:1)
at VM3109 inception-1519300852896.js:1
at w (VM3109 inception-1519300852896.js:1)
at x (VM3109 inception-1519300852896.js:1)
at w (VM3109 inception-1519300852896.js:1)
at E (VM3109 inception-1519300852896.js:1)
at Array.k (VM3109 inception-1519300852896.js:1)
at r (VM3109 inception-1519300852896.js:1)
at s (VM3109 inception-1519300852896.js:1)

ym.modules.define("system.supports.css", [], function(e) { function t(e) { return "undefined" == typeof d[e] ? d[e] = n(e) : d[e] } function n(e) { return r(e) || r(h + a(e)) || r(p.cssPrefix + a(e)) } function r(e) { return "undefined" != typeof i().style[e] ? e : null } function i() { return u || (u = document.createElement("div")) } function a(e) { return e ? e.substr(0, 1).toUpperCase() + e.substr(1) : e } function o(e) { var n = t(e); return n && n != e && (n = "-" + h + "-" + e), n } function s(e) { return l[e] && t("transitionProperty") ? o(l[e]) : null } var u, l = { transform: "transform", opacity: "opacity", transitionTimingFunction: "transition-timing-function", userSelect: "user-select", height: "height" }, c = {}, d = {}, p = ym.env.browser, h = p.cssPrefix.toLowerCase(); e({ checkProperty: t, checkTransitionProperty: function(e) { return "undefined" == typeof c[e] ? c[e] = s(e) : c[e] }, checkTransitionAvailability: s }) }),

http://joxi.ru/a2XnqyoUy83y0r
1b961408a0

this.$ymapEventBus.initMap is not a function

Добрый день. Карта и объекты отрисовываются, но Vue выкидывает ошибку.

[Vue warn]: Error in callback for watcher "coords": "TypeError: this.$ymapEventBus.initMap is not a function"

Как задать масштаб карты?

Как получить объект карты чтобы установить область видимости по расположению всех точек на карте?
Обычно после загрузки карты делаю.
myMap.setBounds(myMap.geoObjects.getBounds())

Ошибка стилей

При использовании версии 6.0.0 и выше, высота дочерних блоков ".ymap-body" устанавливается как 0px, хотя в style передано "height: 245px". Только ".ymap-container" принимает правильное значение.

Рендер:

...
<section class="ymap-container" style="width: 100%; height: 245px;">
  <div id="yandexMap68318" class="ymap-body">
    <ymaps class="ymaps-2-1-60-map" style="width: 1920px; height: 0px;">
      <ymaps class="ymaps-2-1-60-map ymaps-2-1-60-i-ua_js_yes ymaps-2-1-60-map-bg-ru ymaps-2-1-60-islets_map-lang-ru" style="width: 1920px; height: 0px;">
...

Vuejs:

<template>
    <yandex-map
            :coords="[55.0, 40.0]"
            zoom="11"
            style="width: 100%; height: 245px;"
    ></yandex-map>
</template>
<script>
    export default {}
</script>

Параметры для массива placemarks

Ребят, я не совсем пойму как добавить точку на карту с balloon, hintText и т.д.

Если с компонентом всё ок, то в data.placemarks при добавлении объекта следующего вида:

placemarks: [
{
    coords: [54.8, 39.8],
    balloon: {
        header: 'Test baloon',
        body: 'Test body'
    },
    hintContent: 'test hint',
    clusterName: "1",
    icon: 'cinema',
    color: 'green',
    callbacks: { click: function() {
        console.log("click");
    }}
},
...
]

работают только координаты и callback. Насчет clusterName не уверен.
Пробовал balloon добавлять и в properties и в options - без толку.

Пример использования callback

Привет. В новой версии Вы добавили callback для маркеров. Можете показать на небольшом примере как это работает? Скажем событие balloonopen

Усложнение логики

Салют!
Хотел уточнить, зачем надо было так усложнять логику, если можно создавать placemark-и, передавая в компонент карты сразу массив подготовленных PLacemark-в. Тогда функция init может схлопнуться до довольно компактного вида
function init() {
var vm = this;
this.myMap = new ymaps.Map(this.ymapId, {
center: this.coordinates,
zoom: +this.zoom,
behaviors: this.behaviors,
controls: this.controls,
type: 'yandex#${this.mapType}'
});

    var myGeoObjects = new ymaps.GeoObjectCollection();

    vm.placemarks.forEach(function (placemark) {
      var yplacemark =
          new ymaps.Placemark(
              placemark.coordinates,
              placemark.properties,
              placemark.options);

      myGeoObjects.add(yplacemark);
    })

      vm.myMap.geoObjects.add(myGeoObjects);
  }

класс Placemarks может выглядеть типа

export default class Placemark {
constructor(lat, lon) {
this.coordinates = [lat, lon]

this.properties = {};
this.options = {
  iconLayout: "default#image"
};

}
}

Тогда не надо ничего переопределять и можно работать со всеми свойствами карты
Может я чего-то просто недопонял?

ps/ github очень странно парсит код...

pps/ Да, и добавлять маркеры на карту лучше разом, а не по одному

При импорте грузится еще один экземпляр vue

  • При импорте
    import YmapPlugin from 'vue-yandex-maps'
    подгружается еще один экземпляр библиотеки. Это можно заметить по 2м сообщениям "You are running Vue in development mode."
  • При импорте исходника
    import YmapPlugin from 'vue-yandex-maps/src/index.js' все нормально.

Behavior scrollZoom

Добрый день, добавляю в параметры карты: :behavior="['scrollZoom']" , но не появляется прокрутка мышкой

<yandex-map :coords="cities[selectedCity].coords" zoom="10" style="width: 100%; height: 600px;" :cluster-options="{ 1: {clusterDisableClickZoom: true} }" :controls="['trafficControl', 'routeEditor']" :behavior="['scrollZoom']" :placemarks="placemarks" // map-type="map"></yandex-map>

process is not defined

При загрузке страницы ругается на Uncaught ReferenceError: process is not defined at vue-yandex-maps.js:328.

Ререндеринг карты

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

Проблема с отображением маркеров в одном пункте

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

Вот так выглядит если точка одна : https://yadi.sk/i/mdnWYQi03S5fPm

Если много то все падает с ошибками: https://yadi.sk/i/b-tfeiKY3S5fVe

Ошибки: https://yadi.sk/i/ptuNQ-mW3S5fJk

Изменить компонент карты на функциональный

Подумать как превратить компонент карты в функциональный компонент. Проблема в том, что сейчас ссылка на Я.Карту определяется в секции data, которой у функционального компонента быть не должно

У маркера нет options?

Нужно было создать опцию у маркера 'draggable'
Но как выяснилось у него нет такой опции, но есть для массива 'placemarks'

Или я что то не так сделал?

Пытался так:
<ymap-marker marker-type="placemark" :options="{draggable:true}" :coords="[54.62896654088406, 39.731893822753904]" ></ymap-marker>

changeble markers

"Ура! Пишу на русском! )))"

Приветствую!
Вчера хотел прикрутить эту карту. Больно она нравится моему руководству (в плане того, как выглядит она на yandex.ru/maps).

И вот вчера столкнулся с проблемой:
Я расположил единственный маркер на карте по определенной позиции и и дал центровые коорд-ты на карте.
При клике на карту, я хочу, чтобы маркер поменялся. Делал я это тем, что координаты маркера задавал через data:{coords:[lng, lat]}
Кликнув на карту, и получив новые координаты, я изменил значения coords, но вместо ожидаемого - ошибка. (((

И вообще, предусмотрена ли возможность реактивной смены местоположения элементов на карте?

Спасибо!

Не работает с nuxt.js

Благодарю за замечательный плагин, но обнаружилась проблема, плагин не работает с nuxt.js.

Big size of library (not minified)

May be we should minify file, becaurse it's weight more than vue-resource and vue-router together.

Может подумаем о минификации, потому что модуль весит больше чем vue-resource и vue-router вместе взятые
screenshot_150

Проблема с Nuxt.js

При юзании с nuxt.js возникает проблема типа "не могу найти родительский элемент". Проблема в том что рендеринг делается на стороне сервера с одним рандомным айди а на стороне клиента этот айди еще раз присваивается рандомно, и он же передается в яндекс карты, а тот в свой черед не может найти этот элемент. Решил тем что делаю ре-рендеринг этого элемента (карты) с родительского компонента на стороне клиента.

Нулевые значения в "markerFill" и "markerStroke"

Если передать 0 в качестве значения для width или opacity в объектах markerFill и markerStroke, то это приведет к тому что будет присвоено значение по умолчанию, так как 0 будет воспринят как false:

fillOpacity: myMarkers[i].markerFill && myMarkers[i].markerFill.opacity || '1',

Стоит сделать проверку на число, хотя бы так:

fillOpacity: myMarkers[i].markerFill && parseInt(myMarkers[i].markerFill.opacity) >= 0 ? myMarkers[i].markerFill.opacity : '1',

Еще вопрос. Мне необходимо добавить изображение на фон полигона. Есть ли способ сделать это в данный момент или придется добавить строчку и расширить объект markerFill?

fillImageHref: myMarkers[i].markerFill && myMarkers[i].markerFill.imageHref || ''

Добавить функционал конструктора карт

Добрый день.
Было бы очень полезно добавить возможность сделать с помощью данного пакета полноценный конструктор карт, аналогичный https://yandex.ru/map-constructor

То есть необходимо добавить возможность создавать:

  • Метки
  • Полилини
  • Многоугольники

У при добавлении и изменении вызывать события, для получения данных по объектам допустим в json формате. У каждого объекта иметь возможность менять оформление и контент.

Как использовать метод из под callback'ов?

Добрый день!

Вот есть у нас placemark в массиве placemarks
что то вроде этого:
data: () => ({ placemarks: [ { coords: [], options: { draggable: true }, callbacks: { dragend: function (e) { // вот тут проблема } } ] }), methods: { setNewCoord(coord) { this.coords = coords } }

Вот там где "проблема" никак не могу понять как обратиться к "setNewCoord"
пробовал и просто setNewCoord, и setNewCoord(), и this.setNewCoord(), и setNewCoord()

Получилось только вот так:
dragend: (e) => { this.a.methods.setNewCoord(e) }

Но в самом методе setNewCoord уже не получается обратиться к this
Я просто уже сам запутался как обратиться правильно..

Как добавить обработчик события для элемента в detailedControls?

Вот конфиг компонента.

<yandex-map
                :coords="[55.7522200, 37.6155600]"
                zoom="9"
                :controls="['zoomControl']"
                :detailedControls="{ 'searchControl': { options: { provider: 'yandex#search' } } }"
                style="width: 100%;height:500px; margin-top: 30px; margin-bottom: 0.75rem"
                @map-was-initialized="customizeMap"
              >

Я пытаюсь добавить обработчик после инициализации карты в методе customizeMap:

customizeMap(map) { 
    map.controls.get('searchControl').events.add('resultselect', function(e) {
       //instructions
    }
}

Но ничего не получается из-за того, что get('searchControl') возвращает undefined. Хотя get('zoomControl') работает. Есть идеи, как решить проблему?

Что то поломалось?

Раньше все работало нормально, но примерно в декабре вышло обновление и все полетело.
Подумал что я где то накосячил и в итоге просто удалил
Сейчас вновь понадобился данный компонент, но он так и не заработал

Начал разбираться, но ошибки так и не нашел. Но их и нет в консоли.
Подумал может у меня в проекте проблема со стилями или какой то код не дает показать карту.

В итоге создал чистый новый проект, установил только данный плагин. Выключил все браузерные модули(такие как adBlock и остальные)

Скопировал пример из read.me, но в итоге все равно не заработало. Ошибок как не было в консоли, так они и не появились.

В DOM видно что все вставилось, но ничего не показывается
2018-01-13 14 36 34
2018-01-13 14 35 39

Вот весь код:
`

<yandex-map
  :coords="[54.62896654088406, 39.731893822753904]"
  zoom="10"
  style="width: 600px; height: 600px;"
  :behaviors="['ruler']"
  :controls="['trafficControl']"
  :placemarks="placemarks"
  map-type="hybrid"
  @map-was-initialized="initHandler"
>

  <ymap-marker
    marker-type="placemark"
    :coords="[54.7, 39.7]"
    hint-content="Hint content 1"
    :balloon="{header: 'header', body: 'body', footer: 'footer'}"
    :icon="{color: 'green', glyph: 'cinema'}"
    cluster-name="1"
  ></ymap-marker>

  <ymap-marker
    marker-type="placemark"
    :coords="[54.6, 39.8]"
    hint-content="Hint content 1"
    :balloon="{header: 'header', body: 'body', footer: 'footer'}"
    :icon="{color: 'green', glyph: 'cinema'}"
    cluster-name="1"
  ></ymap-marker>

  <ymap-marker
    marker-type="circle"
    :coords="[54.62896654088406, 39.731893822753904]"
    circle-radius="1600"
    hint-content="Hint content 1"
    :marker-fill="{color: '#000000', opacity: 0.4}"
    :marker-stroke="{color: '#ff0000', width: 5}"
    :balloon="{header: 'header', body: 'body', footer: 'footer'}"
  ></ymap-marker>

</yandex-map>
<script>

import { yandexMap, ymapMarker } from 'vue-yandex-maps'

export default {
name: 'app',
components: {
yandexMap, ymapMarker
},
data() {
return {
placemarks: [
{
coords: [54.8, 39.8],
properties: {}, // define properties here
options: {}, // define options here
clusterName: "1",
callbacks: { click: function() {} }
}
]
}
},
methods: {
initHandler(){}
}
}
</script>

<style> </style>

`

Нерабочий балун в компоненте yandex-map

Если задавать метки в параметре placemarks то попытка вызвать балун приводит к ошибке

Uncaught TypeError: Cannot read property 'onClick' of undefined

Пример использования:

<yandex-map
    :coords          = "[54.77, 39.77]"
    zoom             = "16"
    style            = "width: 100%; height: 100%;"
    :controls        = "['fullscreenControl', 'zoomControl']"
    :scroll-zoom     = "false"
    :placemarks      = "[
        {
            coords: [54.77, 39.77],
            properties: {
                balloonContentHeader: 'balloonContentHeader',
                balloonContentBody: 'balloonContentBody',
                balloonContentFooter: 'balloonContentFooter',
                clusterCaption: '<strong><s>Еще</s> одна</strong> метка',
                hintContent: '<strong>Текст  <s>подсказки</s></strong>'
            },
            options: {
                iconLayout: 'default#image',
                iconImageHref: '/assets/images/ui-yandex-map.marker.svg',
                iconImageSize: [38, 44],
                iconImageOffset: [-19, -44]
            }
        }
    ]"
></yandex-map>

Нерабочий балун в компоненте ymap-marker

При использовании кастомной иконки (картинкой) компонента ymap-marker перестает работать балун.

<ymap-marker
      marker-type="placemark"
      :coords="[54.7, 39.7]"
      hint-content="Hint content 1"
      :balloon="{header: '<h1>header</h1>', body: 'body', footer: 'footer'}"
      :icon = "{
            layout: 'default#image',
            imageHref: '/assets/images/ui-yandex-map.marker.svg',
            imageSize: [38, 44],
            imageOffset: [-19, -44]
        }"
      cluster-name="1"
></ymap-marker>

Но например с иконкой из примера он работает:

:icon="{color: 'green', glyph: 'cinema'}"

Вопрос по кластеризации

Есть ли возможность использовать кластеризацию при добавлении маркера через св-во placemark компонента yandexMap?

How to change the language?

Is there a way to change the language?

I tried to add a mapLink property to the component, but it keeps loading the default URL in Russian.

Не критично: Ошибка в IE, Object doesn't support this action

Использую babel-polyfill, однако в консоли осел ругается на:

 Error in callback for watcher "placemarks": "TypeError: Object doesn't support this action"

Watcher-а в моем инстансе у Vue для placemarks нет, только в data пустой массив в начале, потом делаю что-то вроде

let self = this;
//какой-то аякс код
self.map.placemarks.push(newPlacemark);

Ругается то он ругается, но ничего при этом не ломается, т.е. метки выводит без проблем.

capture

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

firefox js error:

[Vue warn]: Error in beforeCreate hook: "TypeError: this.$ymapEventBus is undefined"

chrome js error:

[Vue warn]: Error in beforeCreate hook: "TypeError: Cannot read property 'scriptIsNotAttached' of undefined"


app.js

import Vue from 'vue';
import VueRouter from 'vue-router';

import AppLayout from './AppLayout.vue';
import Home from './pages/Home.vue';
import Contact from './pages/Contact.vue';

Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    base: __dirname,
    routes: [
        { path: '/', name: 'home', component: Home },
        { path: '/contact', name: 'contact', component: Contact }
    ]
});

const app = new Vue({
    router,
    render: function (h) {
        return h(AppLayout);
    }
}).$mount('#app');

Contact.vue

<template>
    <main>
        <p>Contact page</p>

        <yandex-map :coords="[54.62896654088406, 39.731893822753904]"
                    zoom="10"
                    style="width: 600px; height: 600px;">
        </yandex-map>
    </main>
</template>

<script>
    import YandexMap from 'vue-yandex-maps';
    export default {
        components: {
            YandexMap
        }
    }
</script>

v0.3.0 ошибка wather coords

Error in callback for watcher "coords": "TypeError: Cannot read property '$emit' of undefined"

Появляется при любом взаимодействии с компонентом, в котором использованы Яндекс Карты.
При обновлении данных, реактивность отсутствует, ошибок нет.

Не устанавливается 0.7.x версия

при установке версии 0.6.10 все ок.
при установке 0.7.x получаю ошибки вида:

> "c:\Program Files (x86)\Yarn\bin\yarn.cmd" install --latest
yarn install v1.3.2
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
error S:\OpenServer\domains\magazine.loc\node_modules\vue-yandex-maps: Command failed.
Exit code: 1
Command: npm run build
Arguments: 
Directory: S:\OpenServer\domains\magazine.loc\node_modules\vue-yandex-maps
Output:
> [email protected] build S:\OpenServer\domains\magazine.loc\node_modules\vue-yandex-maps
> rollup -c

"rollup" �� ���� ����७��� ��� ���譥�
��������, �ᯮ��塞�� �ணࠬ��� ��� ������ 䠩���.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `rollup -c`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Gemorroj\AppData\Roaming\npm-cache\_logs\2018-02-10T12_35_10_304Z-debug.log

Process finished with exit code 1 at 15:35:10.
Execution time: 4 398 ms.

Отключение скролла, доп функционал

Очень хотелось бы видеть доп функционал, в особенности такие вещи как отключение скролла - behaviors.disable('scrollZoom')
Имхл, без нее на десктопах/ноутах прокрутка страницы с картой превращается в ад.

request new Feature

Привет, очень нравится твой компонент. Может сделаем чтобы можно было как-нибудь строку скопировать из конструктора Яндекс карт. У них же есть такой сервис. Было бы круто добавить эту фичу, чтобы легко было потянуть карты с настройками из конструктора, типа сюда, да:
yandexMapScript.setAttribute('src', 'https://api-maps.yandex.ru/2.1/?lang=ru_RU');

И кстати я не нашел настройку scroll.

Если дашь добро, то я могу реализовать это. Форкнусь от тебя.
Спасибо=)

Отображение карты при переходам по router

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

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.