Search code examples
google-mapsvue.jsmarkervue2-google-maps

How to change active marker icon in vue by clicking


I'm using vue2-google-maps and it would be perfect - to change the marker icon by click on it. I try to write some code but it doesn't work correctly.

Template:

<gmap-map
        ref="mainMap"
        :center="startLocation"
        :zoom="6"
        map-type-id="roadmap"
        style="width: 100%; height: 100%"
        :options="{
            zoomControl: false,
            scaleControl: false,
            mapTypeControl: false,
            fullscreenControl: false,
            streetViewControl: false,
            disableDefaultUi: false
          }"
      >
        <gmap-marker
          v-for="(item, key) in coordinates"
          :key="key"
          :position="getPosition(item)"
          :clickable="true"
          :icon="markerOptions"
          @click="toggleInfo(item, key)"
        ></gmap-marker>
      </gmap-map>

Script:

...

let mapMarker = require('../images/ic-map-marker.svg'),
    mapMarkerActive = require('../images/ic-map-marker-active.svg');

...

startLocation: {
    lat: 49.0384,
    lng: 33.4513
},
coordinates: {
    0: {
        city: City 0,
        lat: '50.4021702',
        lng: '30.3926088'
    },
    1: {
        city: City 1,
        lat: '49.9543502',
        lng: '36.1241697'
    }
},
infoOpened: false,
infoCurrentKey = null,
markerOptions: {
    url: mapMarker
}

...

toggleInfo: function (marker, key) {
    if (this.infoCurrentKey == key) {
        if (this.infoOpened) {
            this.infoOpened = false;
            this.markerOptions = this.mapMarker;
        } else {
            this.infoOpened = true;
            this.markerOptions = this.mapMarkerActive;
        }
    } else {
        this.infoOpened = true;
        this.infoCurrentKey = key;
        this.markerOptions = this.mapMarkerActive;
    }
}

All the markers are changed to active icon by click. Could someone help me please?

Thanks in advance!

Whole code here: https://codesandbox.io/s/map-vue-template-mv33z


Solution

  • all the map markers are referencing the same marker options object. When you change that object then it affects all the map markers.

    you can have a data property called

    selectedKey: null
    

    have a method like:

    getMarkers(key) {
      if (this.selectedKey === key) return this.mapMarkerActive;
      return this.mapMarker;
    },
    

    then you can have

    :icon="getMarkers(key)"
    

    or whatever logic you want to identify the selected marker (personally i'd put an id on the marker coordinate object and then have a selectedMarker data property)

    in my example i have modified your example and the icons now display as you require.

    https://codesandbox.io/s/map-vue-template-q67u0