Polygons that were deleted on Google Maps will reappear once you zoom out

I am working on a map project where I draw polygons. My goal is to remove the previously drawn polygon whenever a new one is being drawn.

Initially, everything seems to work fine. However, when I use the scroll function on the map, the previously drawn polygons reappear.

I am utilizing Vue.js for this project, so it's possible that the issue lies in my incorrect usage of either the Vue API or Google Maps API.

Below is a snippet of my code:

const loader = new Loader({ apiKey: googleApiKey, libraries: ["drawing"] });

let map = ref(null);
const mapDiv = ref(null);
let oldShape = ref(null);

onMounted(async () => {
  await loader.load();

  map.value = new google.maps.Map(mapDiv.value, {
    center: currentPosition.value,
    zoom: 7,
  });

  const drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    drawingControl: false,
    polygonOptions: {
      editable: true,
      fillColor: "#ffff00",
    },
  });

  drawingManager.setMap(map.value);

  google.maps.event.addListener(drawingManager, "overlaycomplete", (event) => {
    if (oldShape.value !== null) {
      oldShape.value.setMap(null);
    }
    const shape = event.overlay;
    shape.type = event.type;
    oldShape.value = shape;
  });
});

When I draw the first polygon, it looks like this: https://i.sstatic.net/502NE.png

Then, when I draw another polygon, the first one disappears, which is good: https://i.sstatic.net/kgpTk.png

However, when I zoom out, the previously removed polygons reappear, which is not the desired behavior: https://i.sstatic.net/FI4ox.png

This unexpected behavior needs to be addressed.

Answer №1

This pertains to the way Vue generates proxies for objects. When nullifying the map, using the toRaw() function can resolve the issue. We encountered a similar problem ourselves.

It's unclear whether you need to invoke it with the oldShape object or oldShape.value, since we follow the Options API.

// before
oldShape.value.setMap(null);
// after
toRaw(oldShape).setMap(null);

Answer №2

By removing the ref from oldShape, it seems to have resolved the issue. Rather than:

let oldShape = ref(null);

the code now reads:

let oldShape = null;

Although I am uncertain why it did not function in the previous setup.

Answer №3

Encountered a similar issue when using oldShape within component data.

data: function() {
  return {oldShape: null}
}

I initially assumed that upon rendering, something would happen and the unlinked oldShape would revert to its original state. Could there be a conflict with Google Polygon objects?

Will update if any new discoveries are made.

UPDATE: The issue seems to stem from a conflict between Google map objects and Vue component properties.

I found a workaround by initializing oldShape in the created hook:

created: function(){
  this.oldShape = null
}

This resolves the conflict without including it as part of the component data.

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

Determine the identifier of the subsequent element located within the adjacent <div> using jQuery

I have a form with multiple input elements. While looping through some elements, I need to locate the id of the next element in the following div. You can find the complete code on jsfiddle $(":text[name^=sedan]").each(function(i){ var curTxtBox = $(thi ...

How can you nest a map within a map in JavaScript?

Here is the code snippet I am working with: _renderChannels() { return this.state.channelsData.map(channelData => { return this.state.channelsStreamData.map(channelStreamData => { return <Channel channelData={channelData} ch ...

Encountering a 500 Internal Server Error message while attempting to access a WebMethod through ajax

I'm encountering an issue with accessing my C# WebMethod in the code behind, resulting in a 500 internal server error. I cannot figure out why it's not working, so any assistance in identifying the problem would be highly appreciated. https://i. ...

Customizing the style of an element in Vue depending on the size of the window

I am struggling to update the appearance of an HTML element when the window size is below 500px. Currently, I have a computed property that sets a background-image for the element. I attempted to use an if statement within the computed property to check if ...

Exploring the possibilities of event-driven programming with Java and Javascript?

When performing computations on a server, the client inputs data that is captured through Javascript. A XMLHttpRequest is made to send this data to the server for processing. What happens if the computation takes an hour and the client leaves or switches o ...

Experiencing memory issues with small programs in Node on macOS?

Currently, I am in the process of learning JavaScript and making use of node to execute JS programs directly from the terminal using this command: node program1.js The issue that I am encountering involves a simple JavaScript program that is supposed to ...

Tips on sorting an array within a map function

During the iteration process, I am facing a challenge where I need to modify certain values based on specific conditions. Here is the current loop setup: response.result.forEach(item => { this.tableModel.push( new F ...

Using jQuery ajax in PHP, the ability to remove retrieved information from a different page is a

I'm currently working on a jQuery AJAX PHP application that allows for adding, deleting, and displaying records using switch case statements to streamline the code. Everything seems to be functioning correctly with inserting and displaying records, bu ...

Transitioning from SJAX to AJAX

I am in the process of updating a portion of my script to use AJAX instead of Synchronous JAX to prevent the page from freezing. My goal is to check if a password is valid before sending it to the server. If the password is not valid, I want the password f ...

I'm experiencing an issue with loading the GeoJSON file on my localhost

I included this vector into my local host code, but the JSON file does not seem to load. geojson_layer = new OpenLayers.Layer.Vector("features", { projection: epsg4326, strategies: [new OpenLayers.Strategy.Fixed()], pro ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

What is the mechanism by which Redux sends state to mapStateToProps?

I'm currently delving into the inner workings of React and Redux, and recently came across FuelSavingsPage.js in this sample project. While I grasp how actions is obtained in mapDispatchToProps, I am uncertain about how state is passed to mapStateToPr ...

Guide to showcasing object characteristics inside an object in Angular2

My USAFacts object contains properties like StateName, as well as objects like State-Bird which hold information about the state bird. If written in JSON, a record of USAFacts would appear as follows: {"StateName": "PA", "State-Bird": [ { "Name": "Ruffed ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Uncertainties surrounding the use of JSON data versus a JavaScript object

As a newcomer to programming, I have ventured into Stack Overflow and W3schools to enhance my skills. Recently, I created a small project for educational purposes. One dilemma is bothering me - is the JSON file I generated actually in proper JSON format o ...

Developing elements in React Native based on JSON data dynamically

Hello everyone, I'm brand new to this forum and just starting out with React Native. I was wondering if someone could help me by providing a code snippet to create form elements (such as an image and a toggle switch) based on JSON data. Here is what ...

I am not seeing anything when I ask for a second perspective

My tech stack includes Ruby on Rails as the framework and Vue.js for data display. I'm using Axios for API requests. To start a project, I used the following command: rails new myapp --webpack=vue This created a folder structure in Rails: app/java ...

Revamp your D3 interactive graph with real-time data updates from the server!

I am looking to enhance a graph in D3 (or another visualization library) by completing the following steps: When a user clicks on an item, like a node within the graph, New data is fetched from the server, The new data is then used to add new edges and n ...

Strategies for Returning Multiple Values from a Function in JavaScript

Thanks in advance I am wondering how to extract multiple values from a code block using JavaScript. I am unsure if I need to use an array or something else as I am new to JS. Please consider the following HTML code: <div class="row"> ...

Executing JQuery asynchronous calls sequentially

Recently delving into the world of Jquery, I've encountered a coding challenge: my code loops through an array and retrieves HTML from an ajax request for each iteration. $.each(arr, function (data) { $.get('/Quote/LoadQuoteItemCost', { ...