How can I remove markers from google maps?

I have been working on a program that dynamically loads JSON data onto a map as markers when the user pans and zooms. However, I am facing an issue where I need to clear the existing markers each time the user interacts with the map in order to load new ones. The current code snippet successfully removes the markers but only when it is attached to a button click event listener.

var features = map.data.addGeoJson(data);
google.maps.event.addDomListener(document.getElementById('removeBtn'), 'click', function () {
    for (var i = 0; i < features.length; i++)
        map.data.remove(features[i]);
});

Here is the code snippet:

function initialize() {
    var mapCanvas = document.getElementById('map-canvas');
    var mapOptions = {
      center: new google.maps.LatLng(39.50, -98.35),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(mapCanvas, mapOptions)
    google.maps.event.addListener(map, 'idle', function() {
        try{
            for (var i = 0; i < features.length; i++) {
                map.data.remove(features[i]); 
            }
        }catch(err){
            console.log("fail")
        }

        $.getJSON("/static/json/data.json", function(data) {
            var features = map.data.addGeoJson(data) {
          });
       });
     });       
   }
    google.maps.event.addDomListener(window, 'load', initialize);

The GEOJSON data:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          -84.375,
          36.31512514748051
        ]
      }
    }
   ]
}

I'm seeking guidance on how to ensure that the 'idle' event listener clears existing markers before loading new ones. How can I approach this?

Answer №1

Instead of storing the features in a separate location, you can rely on a map to manage them.

To remove all features from a map, just run this command:

(function(m){m.data.forEach(function(f){m.data.remove(f);});}(map))

Answer №2

Your code is experiencing a issue due to the presence of the word var before features in the getJSON callback.

We suggest removing that word from your code.

By doing so, you will be modifying the global variable features, which can then be manipulated by your for loop.

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

Incorporate React Components into a traditional HTML, CSS, and JavaScript project

Can I incorporate a React Native Component (https://www.npmjs.com/package/react-native-gifted-chat) into my vanilla JavaScript project? Is it feasible to embed a React Native component within a vanilla JavaScript project? If yes, then what is the process ...

Choosing a table cell in a React Bootstrap table

export class UsersTable extends React.Component { constructor() { super(); this.state = { data: null }; } componentWillMount() { fetch("http://localhost:8081/users/getData") .then(res => res.json()) . ...

Issue with React component not receiving dataThe values are not being

Currently, I am a beginner in using React and as part of my training, I have embarked on a project to create a simple book ranking system. In this project, the user enters the title of the book they would like to vote for. If the input field is left empty, ...

Having trouble getting a new input box to be added when clicking with AngularJS?

I am facing an issue with adding dynamic form fields to the database using PHP. I have utilized angular for this purpose, but only the last form field is getting inserted into the database. To address this, I attempted using arrays and loops to increment a ...

What is the procedure for utilizing Javascript to redirect a user on a website back to the login page if necessary?

Is there a way to redirect a website user back to the login page if they try to access a secure page without logging in first? I'm looking to implement this using JavaScript and cookies. Any suggestions or ideas on how to achieve this seamlessly for t ...

"Handling Errors in JavaScript when a Button Click Event Triggers a

There are 2 buttons intended for "Add to Favorites" and "Remove from Other Favorites". Here is the code snippet: <button type="submit" class="btn btn-warning btn-xs" id="FavoriButonex" data-id="<?php echo $sorid ?>"> <i class="fa fa-hea ...

Angular.js encountered an error at line 13550: [ng:areq] The argument 'popCntrl' is expected to be a function, but it was undefined

I have been diving into learning AngularJS on my own recently, and I've been attempting to create a basic popup feature. However, I keep encountering the error mentioned in the title. While searching for solutions, I haven't found any examples th ...

Animating pseudo-elements using Jquery

I'm having trouble animating the :after pseudo-element of my ul. Below is the CSS code I have: #slider .mypagination ul::after { content: ""; width:25%; bottom: 0; left:0; position: absolute; border-top:1px solid #7accc8; ...

Incorporating an HTML/Javascript game into a reactJS website: A step-by-step

After developing a game using plain javascript and HTML along with a few JS libraries, I find myself inquiring about the process of integrating this game into my ReactJS website. Typically, the game is initiated by opening the index.html file located with ...

Invoke a specific script snippet by its identifier within a React single-page application, causing the content to appear only upon manual

I am currently working on a React application that utilizes a third-party JS script from OneTrust cookie scripts. Unfortunately, the scripts provided are not optimized for single-page applications (SPAs). At the moment, I am simply referencing the script s ...

Can Selenium in JavaScript be used to retrieve child elements from a webpage?

I've been struggling to adapt my JavaScript script for use with Selenium (also in JavaScript). Despite numerous attempts, I haven't been able to find a solution. I've attached an image to better explain my question await chromeDriver.findEle ...

Refining checkboxes with specific criteria

I am struggling with the following code: <form method="post"> <% for(let i = 0; i < websites.length; i++){ let website = websites[i]; %> <fieldset id="site<%= i %>" style="padding-bottom: 0; padding-top: 10p ...

Is there a way to retrieve information from a different object?

Access the code on Plunker I am working with two data structures - ingredients and recipes [{ "id":"1", "name": "Cucumber" }, .. ] and [{ "id":"1", "name": "Salad1", "recipein":[1, 3, 5] }, { ... } ] My goal is to ...

Tips for displaying an element for each item chosen in a multi-select box

I currently have a situation where I am rendering for every selected element within my multiselect angular material selectbox. The rendering process functions correctly when I select an element, but the issue arises when I try to deselect one - it just ke ...

Tips and tricks for personalizing the leaflet Lopup component using vue js

Seeking guidance on customizing the design of the LPopup component in leafletjs. I found a helpful guide at: After inspecting the Lpopup in the dev tools, I tried adding CSS styles to the 'leaflet-popup-content-wrapper' selector (please refer to ...

Cannot adjust expiration date of express-session in browser

In my current project, I am utilizing express-session. Let's say a session has been created between the web browser and the Node.js server with a default expiration time of one hour. At this point, there is a cookie named connect.sid stored in the use ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...

I am facing unexpected results while trying to search for a string array object using elemMatch in Mongoose

I am encountering an issue that I can't seem to resolve. I need to utilize a query search to match the data of one job with user data, but I'm facing some obstacles. The primary challenge is within my query search for the job where the data looks ...

AngularJS: Move forward with controller execution after completion of a looped service method

Currently, I am implementing a networkService in Angular which is responsible for looping while the internet connection is unavailable. The goal is to resume execution once the connection is restored. Below is an example of a controller: MyApp.controller ...

Can you explain how to use a toggle switch to make a select dropdown select a random option?

Currently, I am in the process of setting up a page for a character generator. Users will have the option to randomize traits or input their own. The interface includes toggle switches for the "choice vs random" options for each trait category, as well as ...