Search code examples
javascriptgoogle-mapsvue.jsvuejs2vue2-google-maps

How to use `new google.maps.Marker()` with `vue2-google-maps`


For some reasons, I have to use new google.maps.Marker() with vue2-google-maps, but I don't know how to start since the documents and many people use <GmapMarker ... /> in the HTML part instead.

I've tried to search but the document doesn't cover this.

Right now my code looks like this, it doesn't have any error but it doesn't work either (the map is present but the marker isn't shown):

<template>
  <div style="height: 100%; width: 100%;">
    <GmapMap
      :center="{ lat: 0, lng: 0 }"
      ref="mapRef"
    >
    </GmapMap>
  </div>
</template>
<script>
import * as VueGoogleMaps from 'vue2-google-maps';

export default {
  computed: {
    google: VueGoogleMaps.gmapApi,
  },
  methods: {
    init() {
      new this.google.maps.Marker({
        position: {
          lat: 0,
          lng: 0
        },
        map: this.$refs.mapRef,
      });
    }
  },
  async mounted() {
    this.init()
  },
}
</script>

Solution

  • Ok, I figured out. Here's what I did:


    Create a map variable in data()

    data() {
      return {
        map: undefined,
      }
    },
    

    Set it using this function in mounted()

    mounted() {
      this.$refs.mapRef.$mapPromise.then((map) => {
        this.map = map;
        this.init();
      });
    },
    

    Now, Bob's your uncle, you can use this.map where ever you want

    methods: {
      init() {
        new this.google.maps.Marker({
          position: {
            lat: 0,
            lng: 0
          },
          map: this.map,
        });
      },
    }