vue.jsgoogle-mapsinertiajspinia

Why is removing a google map Polyline not working for google maps


I have a bug where when I plot a polyline on a google map and I try to remove it It is not removed. I am wondering if this seems to be because I am using pinia. And how would I go about it

import { defineStore } from 'pinia'
import { ref, watch } from 'vue';

export const useMapStore = defineStore('map', () => {
    const mapContainer = ref(null);
    const googleMap = ref(null);
    const googlePolyline = ref(null)


    watch([() => googlePolyline.value ], ([newGooglePolyline],[oldGooglePolyline]) => {
      if(oldGooglePolyline){
          oldGooglePolyline.setMap(null)
      }
      if(newGooglePolyline){
          newGooglePolyline.setMap(googleMap.value)
      }
    })

    const plotHistory = (locations, currentPosition, pathId = null ) => {
        locations = locations.map((position) => {
            return { lat: position.latitude, lng: position.longitude }
        })
        // Draw lines connecting the markers
        googlePolyline.value = new google.maps.Polyline({
          path: locations,
          strokeColor: "#FF0000",
          strokeOpacity: 1.0,
          strokeWeight: 2,
        });
    }


    const clearPolyline = () => {
        if (googlePolyline.value) {
            googlePolyline.value = null;
        }
    }


}

It seems like multiple lines might be. being created but I can't seem to figure out if this is the case.

Here a GitHub link to a minimal project I have created to reproduce the issue.

https://github.com/iamafasha/google-map-vue-pinia


Solution

  • Turns out it's because of how vue creates proxy objects. as John mentions in his answer to this question.

    Here is what I did to fix the issue

    watch([() => googlePolyline.value ], ([newGooglePolyline][oldGooglePolyline]) => {
          if(oldGooglePolyline){
            console.log("oldGooglePolyline set to null", oldGooglePolyline)
            toRaw(oldGooglePolyline).setMap(null)
          }
          if(newGooglePolyline){
            console.log("newGooglePolyline set to googleMap")
              toRaw(newGooglePolyline).setMap(googleMap.value)
          }
        })
    

    So I had to use the toRaw method provided by vue, to access the actual object created by vue instead of using the Proxy.

    Here is the documentation on it.