Search code examples
google-mapsvuejs2vue2-google-maps

How to fit a circle inside a Google Maps when using vue2-google-maps?


I found on this question that you can use fitBounds() to make a circle fit into a map. I tried to use it while using vue2-google-maps and it didn't work. How would be the equivalent for it while using this library?


Solution

  • For that matter Google Maps Circle object could be accessed via $refs attribute:

    <GmapCircle
        ref="circleRef" 
        :center="{ lat: 52.521248, lng: 13.399038 }"
        :radius="400000"
        :visible="true"
        :options="{fillColor:'blue',fillOpacity:0.2}"
    />
    

    and then map viewport set the circle bounds like this:

    mounted: function() {
        this.$refs.circleRef.$circlePromise.then(() => {
            const {$circleObject} = this.$refs.circleRef; //get google.maps.Circle object
            const map = $circleObject.getMap(); //get map instance 
            map.fitBounds($circleObject.getBounds());
       })
    }
    

    Example

    <template>
      <div>
        <GmapMap :center="center" :zoom="zoom">
          <GmapCircle
            ref="circleRef" 
            :center="{ lat: 52.521248, lng: 13.399038 }"
            :radius="400000"
            :visible="true"
            :options="{fillColor:'blue',fillOpacity:0.2}"
          ></GmapCircle>
        </GmapMap>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          zoom: 5,
          center: { lat: 59.339025, lng: 18.065818 }
        };
      },
      mounted: function() {
        this.$refs.circleRef.$circlePromise.then(() => {
            const {$circleObject} = this.$refs.circleRef; //get google.maps.Circle object
            const map = $circleObject.getMap();
            map.fitBounds($circleObject.getBounds());
        })
      }
    };
    </script>
    
    <style>
    .vue-map-container {
      height: 640px;
    }
    </style>