[Vuejs]-Adding Multiple Markers on Vue JS Google Maps

0👍

You can use the gmap-vue plugin for VueJS to add multiple markers by clicking on the map.

First, initialize your Google Map, and make sure to add an array of markers: [] that will contain all the markers that you will be adding on the map:

<template>
  <div>
    <gmap-map
      :center="center"
      ref="mmm"
      :zoom="12"
      style="width: 100%; height: 400px"
      @click="addMarker"
    >
      <gmap-marker
        :key="index"
        v-for="(m, index) in markers"
      />
    </gmap-map>
  </div>
</template>


export default {
  name: "GoogleMap",
  data() {
    return {
      center: { lat: 45.508, lng: -73.587 },
      markers: [],
    };
  },
  
};

You can add markers by calling the @click="addMarker" event on <gmap-map>. Then, on the your methods you can add the addMarker(event) function where you should be able to get the click coordinates from the map. You can now

Here is what it looks like:

methods: {
    addMarker(event) {
      const marker = {
        lat: event.latLng.lat(),
        lng: event.latLng.lng(),
      };
      console.log(marker);
      this.markers.push({ position: marker });
      this.$refs.mmm.panTo(marker);
      //this.center = marker;
  },
},

Here is a working codesandbox for your reference, just put your API key on the main.js file: https://codesandbox.io/s/gifted-fast-b41ps

0👍

You can use- but you don’t need any plug-in. It doesn’t really save time in this use-case imho.

With the standard implementation it would look something like that:

this.yourPOIs.forEach(poi => {
    var myLatLng = { lat: poi.latitude, lng: poi.longitude };
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: this.myMap,
        title: poi.annotation
        // you can also add data here with key names that are not in use like for example "uuid: 1" so you can access that data later on if you click on markers or iterate through them
    });
    marker.addListener('click', function() {
        console.log(marker.uuid); // if you want to react on clicking on a marker
    });
    this.addedMarkers.push(marker);
});

myMap being the map object written in a local variable instead of writing it in a let-variable (you will probably need to access the map later on so you better safe them in the local data of the component or your vuex store).

That’s also why i pushed the markers in an array of the component. By that you can later on do this to delete the markers again (for e.g. updating the map):

this.addedMarkers.forEach(marker => {
     marker.setMap(null);
});

Leave a comment