Answer the question
In order to leave comments, you need to log in
How to pass a Yandex.map instance to vuex so that you can add markers on click in the methods of the Vue component?
Initialized the map in the mounted hook.
The map opens and centers on the user's location. How can I get a map instance so that I can add markers in the methods of the Vue component, for example, on click?
Here is the map component code:
<template>
<div
id="map"
class="ymap-container"
@click="onClick"
></div>
</template>
<script>
import {loadYmap} from 'vue-yandex-maps'
export default {
name: 'LocationMap',
data() {
return {
name: '',
coords: [],
settings: {
apiKey: '',
lang: 'ru_RU',
coordorder: 'latlong',
version: '2.1'
},
myMap: {}
}
},
methods: {
onClick(e) {
},
},
async mounted() {
await loadYmap({...this.settings, debug: true})
ymaps.ready(ymaps.geolocation.get()
.then((res) => {
const [long, lat] = res.geoObjects.position
this.myMap = new ymaps.Map("map", {
center: [long, lat],
zoom: 7
})
})
.catch(e => {
console.log('Ошибка: ' + err)
}))
}
}
</script>
<style scoped>
.ymap-container {
width: 750px;
height: 500px;
border: 1px solid #ccc;
border-radius: 3px;
}
</style>
Answer the question
In order to leave comments, you need to log in
No need to pull the card directly. Make an array with marker data, fill it on click, and create instances of the marker component based on it:
import { yandexMap, ymapMarker, loadYmap } from 'vue-yandex-maps';
components: {
yandexMap,
ymapMarker,
},
data: () => ({
coords: null,
markers: [],
settings: { /* ... */ },
}),
methods: {
onClick(e) {
this.markers.push({
id: 1 + Math.max(0, ...this.markers.map(n => n.id)),
coords: e.get('coords'),
});
},
},
async mounted() {
await loadYmap({ ...this.settings, debug: true });
ymaps.geolocation.get().then(res => {
this.coords = res.geoObjects.position;
});
},
<yandex-map
v-if="coords"
:coords="coords"
@click="onClick"
>
<ymap-marker
v-for="n in markers"
:key="n.id"
:marker-id="n.id"
:coords="n.coords"
></ymap-marker>
</yandex-map>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question