What is the best way to remove current markers on google maps?

This is how I implemented it in my project.

The issue I'm facing is that the clearAirports function does not seem to clear any existing markers on the map or show any errors in the Google console.

googleMaps: {
    map: null,
    init: function () {
        var self = this;
        var $google_maps_item = $('#gmaps');
        if  ( $google_maps_item.length ) { 

            var mapOptions = {
                zoom: 5,
                center: new google.maps.LatLng( 39.615794, 2.998049 ),
                scrollwheel: false,
                zoomControl: false,
                mapTypeControl: false,
                scaleControl: false,
                streetViewControl: false,
                rotateControl: false,
                disableDefaultUI: true
             };
             self.map = new google.maps.Map(document.getElementById("gmaps"), mapOptions);
             var marker = new google.maps.Marker({
                 position: new google.maps.LatLng($google_maps_item.data('lat'), $google_maps_item.data('long')),
                 map: self.map,
                 icon: {
                     path: "M27.648 -41.399q0 -3.816 -2.7 -6.516t-6.516 -2.7 -6.516 2.7 -2.7 6.516 2.7 6.516 6.516 2.7 6.516 -2.7 2.7 -6.516zm9.216 0q0 3.924 -1.188 6.444l-13.104 27.864q-0.576 1.188 -1.71 1.872t-2.43 0.684 -2.43 -0.684 -1.674 -1.872l-13.14 -27.864q-1.188 -2.52 -1.188 -6.444 0 -7.632 5.4 -13.032t13.032 -5.4 13.032 5.4 5.4 13.032z",
                     scale: 0.6,
                     strokeWeight: 0.2,
                     strokeColor: 'black',
                     strokeOpacity: 1,
                     fillColor: '#003547',
                     fillOpacity: 0.85,
                 }
             });         
             self.drawAirports();

        }
    },
    drawAirports: function () {
        var self = this;
        var markers = [];



        var $airports = $('.airport_list ul li:visible');
        var airports = [];

        console.log( 'Detected ' + $airports.length + ' visible airports' );

        $airports.each( function () {
            var airport = {
                'airport' : $(this).data('titulo'),
                'lat' : $(this).data('lat'),
                'long' : $(this).data('long'),
                'href' : $(this).data('href')
            }
            airports[airports.length] = airport;
        });


        var infobox = null;
        for (var i = 0; i < airports.length; i++) {
              (function (airport) {
                  console.log ( base_url + 'img/gmaps/marker.png' ); 
                  var marker = new google.maps.Marker({
                      position: new google.maps.LatLng(airport.lat, airport.long),
                      map: self.map,
                      title: airport.airport,
                      icon: base_url + 'img/gmaps/marker.png',
                      visible: true
                  });

                  google.maps.event.addListener(marker, 'click', function () {
                      if(infobox) {
                          infobox.close();
                      }
                      infobox = new InfoBox({
                          content: '<h3>' + airport.airport + '</h3><a class="info" href=""><span>Information</span></a><a class="bags" href=""><span>Baggage</span></a>',
                          disableAutoPan: false,
                          maxWidth: 150,
                          pixelOffset: new google.maps.Size(-212, -150),
                          zIndex: null,
                          boxStyle: {
                              width: "280px"
                          },
                          closeBoxMargin: "0",
                          closeBoxURL: base_url + "img/gmaps/close.png",
                          infoBoxClearance: new google.maps.Size(1, 1)
                      });
                      infobox.open(map, this);
                      map.panTo(marker.position);
                  });

                  markers.push(marker);
              })(airports[i]);
          }
    },
    clearAirports: function () {
        google.maps.Map.prototype.clearMarkers = function() {
            if ( this.markers !== undefined && this.markers !== 'undefined' ) {
                console.log( this.markers.length + ' Markers to clear' );
                for(var i=0; i < this.markers.length; i++){
                    this.markers[i].setMap(null);
                }
                this.markers = new Array();
            }               
        };

        this.map.clearMarkers();
    }
}

Not sure why the clearAirports function is not working as expected. I found the code snippet from here.

Answer №1

Include markers within the googleMaps object as a property, populate it with all markers, and make some adjustments to the clearAirports function:

googleMaps: {
    map: null,
    markers: [], //STORE MARKERS HERE
    init: function () {
        var self = this;
        var $google_maps_item = $('#gmaps');
        if ($google_maps_item.length) {

            var mapOptions = {
                zoom: 5,
                center: new google.maps.LatLng(39.615794, 2.998049),
                scrollwheel: false,
                zoomControl: false,
                mapTypeControl: false,
                scaleControl: false,
                streetViewControl: false,
                rotateControl: false,
                disableDefaultUI: true
            };
            self.map = new google.maps.Map(document.getElementById("gmaps"), mapOptions);
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng($google_maps_item.data('lat'), $google_maps_item.data('long')),
                map: self.map,
                icon: {
                    path: "M27.648 -41.399q0 -3.816 -2.7 -6.516t-6.516 -2.7 -6.516 2.7 -2.7 6.516 2.7 6.516 6.516 2.7 6.516 -2.7 2.7 -6.516zm9.216 0q0 3.924 -1.188 6.444l-13.104 27.864q-0.576 1.188 -1.71 1.872t-2.43 0.684 -2.43 -0.684 -1.674 -1.872l-13.14 -27.864q-1.188 -2.52 -1.188 -6.444 0 -7.632 5.4 -13.032t13.032 -5.4 13.032 5.4 5.4 13.032z",
                    scale: 0.6,
                    strokeWeight: 0.2,
                    strokeColor: 'black',
                    strokeOpacity: 1,
                    fillColor: '#003547',
                    fillOpacity: 0.85,
                }
            });
            self.markers.push(marker); //PLACE MARKER IN ARRAY      
            self.drawAirports();

        }
    },
    drawAirports: function () {
        var self = this;

        var $airports = $('.airport_list ul li:visible');
        var airports = [];

        console.log('Detected ' + $airports.length + ' visible airports');

        $airports.each(function () {
            var airport = {
                'airport': $(this).data('titulo'),
                'lat': $(this).data('lat'),
                'long': $(this).data('long'),
                'href': $(this).data('href')
            }
            airports[airports.length] = airport;
        });

        var infobox = null;
        for (var i = 0; i < airports.length; i++) {
            (function (airport) {
                console.log(base_url + 'img/gmaps/marker.png');
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(airport.lat, airport.long),
                    map: self.map,
                    title: airport.airport,
                    icon: base_url + 'img/gmaps/marker.png',
                    visible: true
                });

                google.maps.event.addListener(marker, 'click', function () {
                    if (infobox) {
                        infobox.close();
                    }
                    infobox = new InfoBox({
                        content: '<h3>' + airport.airport + '</h3><a class="info" href=""><span>Information</span></a><a class="bags" href=""><span>Baggage</span></a>',
                        disableAutoPan: false,
                        maxWidth: 150,
                        pixelOffset: new google.maps.Size(-212, -150),
                        zIndex: null,
                        boxStyle: {
                            width: "280px"
                        },
                        closeBoxMargin: "0",
                        closeBoxURL: base_url + "img/gmaps/close.png",
                        infoBoxClearance: new google.maps.Size(1, 1)
                    });
                    infobox.open(map, this);
                    map.panTo(marker.position);
                });

                self.markers.push(marker); //ADD TO MARKERS ARRAY
            })(airports[i]);
        }
    },
    clearAirports: function () { 
        console.log(this.markers.length + ' Markers need to be cleared');
        for (var i = 0; i < this.markers.length; i++) {
            this.markers[i].setMap(null);
        }
        this.markers = new Array();
    }
}

Answer №2

   <!DOCTYPE html>
    <html>
      <head>
        <title>Remove Markers</title>
        <style>
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
          }
          #map {
            height: 100%;
          }
          #floating-panel {
            position: absolute;
            top: 10px;
            left: 25%;
            z-index: 5;
            background-color: #fff;
            padding: 5px;
            border: 1px solid #999;
            text-align: center;
            font-family: 'Roboto','sans-serif';
            line-height: 30px;
            padding-left: 10px;
          }
        </style>
      </head>
      <body>
        <div id="floating-panel">
          <input onclick="clearMarkers();" type=button value="Hide Markers">
          <input onclick="showMarkers();" type=button value="Show All Markers">
          <input onclick="deleteMarkers();" type=button value="Delete Markers">
        </div>
        <div id="map"></div>
        <p>Click on the map to add markers.</p>
        <script>

          // Example code demonstrating how to manage markers on a Google Map.
     
      
        </script>
        <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
        </script>
      </body>
    </html>

Answer №3

To ensure visibility, declare the markers array within a window's visible area. This way, you can easily iterate over the array to set relevant maps to null.

  // Place this code outside the drawAirports function
  var markers = [];

Next, loop through the markers array using a for loop:

  for (var i = 0; i < markers.length; i++) {
    markers[i].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

In JavaScript, the return statement is used to halt the execution of any subsequent statements

I encountered a situation where I need to stop the execution of the next function call if the previous function has a return statement. However, I noticed that even though there is a return statement in the "b" function below, the next function call still ...

How can you create an animation that plays forward on the first click and then reverses on the second

After coming across numerous similar questions, I realize that most of them refer to the outdated .toggle() function. My main challenge lies in achieving the desired effect where div#p moves right on the first click and then returns to its original positio ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...

Incorporate a pause into a JavaScript function

Consider the following function: $(document.body).ready(function() { var o = $(".hidden"); $(".about_us").click(function() { o.hasClass("visible") ? o.removeClass("visible") : o.addClass("visible"); }); }); I am looking to add a delay to this f ...

When working with AngularJS, I noticed that the service function within a loop is only executed after all iterations have been completed

Controller Page $scope.page = { '1' : "small", '2' : "large", '3': "medium" }; $scope.form.appraisal_id = "abc123"; $scope.form.user_id = "efg123"; for(var prop in $scope.page ...

Analyzing XBRL documents using JavaScript

Looking to extract information from XBRL files like the one found here, I came across a promising npm module called parse-xbrl that claims to be capable of parsing XBRL files. Here is the code snippet I used for implementation: var ParseXbrl = require(&ap ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

issue involving extension that interrupts downloads

Trying to develop a browser extension that can intercept downloads and automatically rename them. manifest.json: { "name": " Book Renamer", "description": "Automatically rename downloaded ebooks from gutenberg.or ...

How can I convert a string to an integer in Node.js/JavaScript in terms of cardinality?

Imagine a scenario where a user can input any string such as "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. The goal is to assign an integer value to each of these strings: "1st" -> 0 "2nd" -> 1 "third" -> 2 "fourth" -> 3 "fifth" -&g ...

What is the best method to generate a distinct identifier for individual input fields using either JavaScript or jQuery?

I have attempted to copy the table n number of times using a for loop. Unfortunately, the for loop seems to only work on the first iteration. I am aware that this is due to not having unique IDs assigned to each table. As a beginner, I am unsure how to cre ...

Revise the validation process for the drop-down menu and input field

Looking for help with text field validation based on a dropdown selection. There are two scenarios to consider: 1. User changes dropdown value and then enters text in the field. 2. User enters text in field and then changes dropdown. I've written cod ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...

Display search results in Rails without needing to refresh the entire tab

I have a search functionality incorporated within a Bootstrap tab, and I aim to display the search results dynamically without reloading the entire page, specifically within the tab itself. Despite adding 'remote: true' to the form_tag and incor ...

How to creatively position custom arrows in a React JS Nuka Carousel

Seeking assistance on properly positioning custom arrows within the Nuka Carousel component. After combining the decorators, I found that both of my arrows are appearing side by side. How can I address this issue? My goal is to have one arrow positioned in ...

"During the testing phase, the req.body object is found

I'm currently performing unit testing on my express application using Mocha and Chai. However, when I attempt to use req.body in the test file to parse the object, I only receive undefined in the testing results. In my server (app.js), I have alread ...

transferring documents using multer

As a novice in JavaScript, I am exploring the use of multer for file uploads. Below is my current code: let express = require('express'); let im = require('imagemagick'); let gm = require("gm").subClass({ imageMagick: true }); let ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

useEffect does not trigger a rerender on the primary parent component

I am facing an issue where the main parent component does not re-render when I change the state 'click button' in another component while using useEffect. Oddly enough, the main <App /> component only re-renders properly when I reload the p ...

Accessing the ViewModel property of a parent component from the ViewModel of its child in Aurelia

Having a scenario with two distinct components: <parent-component type="permanent"> <div child-component></div> </parent-component> class ParentComponentCustomElement { @bindable public type: string = "permanent"; } clas ...

What is the best way to securely transfer API keys to a React frontend for use in a React component?

I'm currently working with @react-google-maps/api to develop a map component in React. To load the component, we have to provide an API key for useJsApiLoader. How can I securely manage the API key so it's not exposed on the frontend? (Using an E ...