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

How to add polygon to a map


I am using Vue.js and vue2-google-maps to display a map and a polygon, but the function to show the polygon did not work. I am new to this framework.

I tried using the usual step from google maps tutorial using

map.data.add({geometry: new google.maps.Data.Polygon(path)

but it did not work.

here is the script:

mounted() {
    this.addPolygon();
  },

  methods: {
    addPolygon(){
      var poly = new google.maps.Polygon({
        paths: this.paths,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
      });
      console.log(this.poly);
      this.$refs.map.$mapObject.data.add({geometry: new google.maps.Data.Polygon([this.poly])});
    }
  }

how do I make this work?


Solution

  • Based off of the library's examples, it looks like you can add a simple polygon on your map like this:

    <gmap-map
      :center="center"
      :zoom="13"
      style="width:100%;  height: 400px;" 
    >
      <gmap-polygon :paths="paths"></gmap-polygon>
    </gmap-map>
    

    For guidance and demonstration you can check out this working codesandbox. Remember to add your own API key for the map to load correctly.

    Hope this helps!