Removing Google map markers using Vue

Utilizing the Google API to showcase a map, markers, and polygons poses a challenge.
Adding new markers without removing the previous ones is causing an issue.

The map, markers & polygons data are stored in my data state.

data() {
    return {
    google: window.google,
    map: null,
    activeInfoWindow: null,
    polygons: [],
    markers: []
    }
},

Attempts to remove the previous markers using marker.setMap(null) before displaying new markers have been made.

filtersResults: function (filterResults) {
    // REMOVING PREVIOUS ACTIVE MARKER
    this.markers.map((marker) => marker.setMap(null))
},

Even clearing the markers array doesn't solve the issue. The markers persist on the map. https://i.sstatic.net/Wtvli.png https://i.sstatic.net/SamIs.png

The setMap method is not returning undefined as confirmed by console.logging(marker.setMap).

ƒ (c){try{this.set(a,b(c))}catch(d){_.Pe(_.Oe("set"+_.Bf(a),d))}}
  data() {
      return {
        google: window.google,
        map: null,
        activeInfoWindow: null,
        polygons: [],
        markers: []
      }
    },
    async mounted() {
      const { LatLng, Map, MapTypeId } = this.google.maps
        this.map = new Map(document.getElementById('map'), {
            zoom: 10,
            center: new LatLng(process.env.INITIAL_LAT, process.env.INITIAL_LNG),
            mapTypeId: MapTypeId.ROADMAP
        })
    },
    watch: {
      filtersResults: function (filterResults) {
        // REMOVING PREVIOUS ACTIVE MARKER
        this.markers.map((marker) => marker.setMap(null))
        this.markers = []
      },
      assets: {
        handler: function (newValue) {
          const { map } = this
          if (isNotNullAndUndefined(newValue) && map) {
            
            // ! GENERATING MARKERS HERE
            this.markers = newValue.map((value) => {
              const { location } = value
              return this.generateMarkers({
                latitude: dotFormat(location.lat),
                longitude: dotFormat(location.lng),
                details: value
              })
            })
          }
        },
        immediate: true
      }
    },
    methods: {
      generateMarkers({ latitude, longitude, details }) {
        const { map, google } = this
        const { LatLng, Marker } = google.maps

        const marker = new Marker({
          position: new LatLng(latitude, longitude),
          draggable: false
        })

        marker.setMap(map)
        return marker
      },
    }
  }

Answer №1

In the scenario where we store the Markers within the markers array, vue.js 3 automatically transforms them into Proxy objects.
This can create a complication when attempting to later execute Proxy.setMap(null); Google Maps seems to have issues with this, possibly due to the fact that the Proxy object is not strictly identical (===) to the original Marker object initially added to the map.

To address this issue, I discovered a workaround which involves utilizing the toRaw() method before interacting with any Google Maps objects that had been converted to Proxy objects:

import {toRaw} from 'vue';

this.markers.map((marker) => toRaw(marker).setMap(null))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Syntax for retrieving response with jQuery AJAX

Currently, I am in the process of working on an AJAX request that triggers a URL when a specific button is clicked. The fundamental aspects are running smoothly, ensuring that the GET request is activated towards the URL upon button click. I have also cros ...

show information from json onto an html page with the help of jquery

I'm looking to showcase buttons from a JSON file within a simple block. Here's the JSON data for movies: { "movies": [ { "title": "Mena", "movieid": "1", ...

The boolean validation function appears to be malfunctioning in the NodeJS environment

I am currently working on developing the node js API and I am fetching data using a URL query. get_posts_default?pageId=ge4JqBn9F0srzHnVFHmh&asking_post=false&asking_responce=false&maxSort=-1&minSort=-1&limit=20 This function is respo ...

What is the best way to use JavaScript to click on a block and retrieve its attribute value?

Struggling to capture the data-id attribute value of each item on click, despite researching online. Seeking guidance as I navigate the learning process and encounter programming frustrations. document.addEventListener("click", handle); const demo = e. ...

What steps should be taken to generate a successful pop-up window post registration in PHP?

beginning section continuation What is the best way to design an effective popup window? ...

Troubleshooting issue: PHP INSERT Prepared statement not working when using AJAX

Currently, I am trying to construct an INSERT statement using AJAX along with a prepared statement in PDO. This is my first attempt at combining AJAX and PDO, so there might be mistakes due to lack of experience. In its current state, I keep encountering ...

How to send the value of a JavaScript loop variable to PHP using AJAX

How can I send variables in a loop to a PHP file using AJAX? var lat; var lng; var array = [22.399602, 114.041176, 22.344043, 114.0168, 22.327529, 114.087181]; console.log(array); for (var i = 0; i < 6; i += 2) { lat = array[i]; console.log("l ...

Eliminate all the zeros from the date string

Trying to work with a string that is in the format '01/02/2016' and my goal is to eliminate the leading zeros so I end up with '1/2/2016' using regex. So far, I have attempted '01/02/2016'.replace(/^0|[^\/]0./, '&ap ...

Is a local snapshot stored by Firebase Firestore?

In my chat room application, I am utilizing Firebase Firestore for data storage. One of the functions in my app handles sending messages to Firebase like this: const sendMessageHandler = message => { if (message) { firestore() .collection(` ...

Error message "Property 'name' does not exist on type '{}'" is encountered when using Ionic/Angular HttpClient and no data type is specified

While working on my Ionic project, I encountered an error in Angular when trying to fetch data from an API using HttpClient. The error message that popped up was 'Property 'name' does not exist on type '{}'.'. Below is the cod ...

Unit testing in Angular JS is crucial, especially when testing functions in services that do not return any values

Apologies if this has been asked before, but I couldn't find a solution to my issue. I need to create tests for a service within an Angular JS application. The main function of the service returns and is used as an external method. There are also a ...

Tips for managing the output of asynchronous calls in JavaScript?

I have three different models and I need to fetch information from a MongoDB document based on sex, race, and age. The issue is that the find method operates asynchronously. How can I handle this situation effectively? Sex.find(function(err, sexModels) ...

What are some additional options for sourcing images in the img HTML tag?

I am facing an issue where I have two alternative images, with one image set as the default if the first two are not found. <img src='image1.png' onError="this.onerror=null;this.src='image2.png';" onError=" ...

Angular's directives do not trigger the 'viewContentLoaded' event

I recently created a 'light-gallery' directive that relies on the jquery.lightgallery.js plugin to initialize the $.fn.lightGallery() functions. It is crucial for these functions to be executed after the directive template has been compiled and l ...

What are the alternative methods to execute a React.js application without using react-scripts?

After creating my React.js app using the command below: npx create-react-app my-app I'm now looking to modify the package.json script section to run the app without react-scripts. How can I achieve this? "scripts": { "start&quo ...

Storing selected checkbox values in an sqlite database using JavaScript

I am working on an ejs form that includes multiple checkboxes for users to select their interests. These selections should be saved to a sqlite Database table. The table is being created with bootstrap: db.exec('CREATE TABLE interests(interest text)& ...

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...

Access the initial array and the primary element within an array containing multiple arrays

How can I access the first value in the first array of an array of arrays? questions: [ [ 'Purchase only', 'Sale and purchase', 'Sale only', 'Remortgage' ] ...

An iframe perfectly centered both horizontally and vertically, featuring a 16:9 aspect ratio and utilizing the maximum screen space without any cropping

Specifications: It is mandatory for the iframe to be enclosed within a div container as shown in the code below. The container should have the flexibility to adjust to any valid width and height using the vw and vh viewport units. Check the code provided ...

Unable to assign the value of 'innerHTML' to a null property during an AJAX request

I have searched through numerous articles on this site, but I haven't been able to find the solution I'm looking for. Every time I click a cell in my custom div table, I receive the frustrating message "Cannot set property 'innerHTML' ...