Even after deleting the circle from the Google Map, the label still persists within the Google Map Javascript API

Even after removing circles on the Google Map, the labels still persist. I use InfoBox to display labels on circles like this:

myOptions.content = datadetail[i].Count;
var ibLabel = new InfoBox(myOptions);
ibLabel.open(map);

I am trying to clear the circles in the ZoomIn/ZoomOut event under certain conditions. The circles are cleared but the labels remain visible. Here is my complete script. Thank you.

<script>
    var gmarkers = [];
    var gmlist = [];
    var fill_color_val = '#3888ff';
    var labelText = "1";
    var currentZoom = 0;
    $(function () {
        function initialize_map() {
            var mapProp = {
                minZoom: 11,
                maxZoom: 20,
                center: new google.maps.LatLng(16.7803886, 96.1844148),
                zoom: 12,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map"), mapProp);
            bindMarkerOnMap("level_0");
        }

        initialize_map();

        map.addListener('zoom_changed', function () {
            currentZoom = map.getZoom();
            if (currentZoom <= 12) {
                ClearMapMaker();
                console.log(map.getZoom());
                bindMarkerOnMap("level_0");
            } else if (currentZoom >= 13) {
                console.log("level_1 fired + " + currentZoom);
                ClearMapMaker()
                console.log(map.getZoom());
                bindMarkerOnMap("level_1");
            }else if (currentZoom >= 15) {
                bindMarkerOnMap("level_2");
            }
        });

    });

    function bindMarkerOnMap(level) {
        console.log(level);
        if (level == "level_0") {
            console.log("level_0 binding");
            for (var i = 0; i < data.length; i++) {
                var latlng = new google.maps.LatLng(data[i].Lat, data[i].Long);

                var myOptions = {
                    content: labelText,
                    boxStyle: {
                        border: "none",
                        textAlign: "center",
                        fontSize: "10pt",
                        width: "50px"
                    },
                    disableAutoPan: true,
                    pixelOffset: new google.maps.Size(-25, -5),
                    position: latlng,
                    closeBoxURL: "",
                    isHidden: false,
                    pane: "floatPane",
                    enableEventPropagation: true
                };

                // Add circle overlay and bind to marker
                var circle = new google.maps.Circle({
                    map: map,
                    radius: 1600, 
                    fillColor: fill_color_val,
                    strokeColor: '#69DAED',
                    strokeWeight: 2,
                    fillOpacity: 1,
                });

                var marker = new google.maps.Marker({
                    position: latlng,
                    title: data[i].Author,
                    draggable: false,
                    map: map
                });
                marker.setVisible(false);

                circle.bindTo('center', marker, 'position');

                google.maps.event.addListener(circle, 'click', getInfoCallback(map, latlng));

                myOptions.content = data[i].Count;
                var ibLabel = new InfoBox(myOptions);
                ibLabel.open(map);
                gmarkers.push(circle);
                gmlist.push(marker);
            }
        } else if (level == "level_1") {
            console.log("level_1 binding");
            for (var i = 0; i < datadetail.length; i++) {
                var latlng = new google.maps.LatLng(datadetail[i].Lat, datadetail[i].Long);

                var myOptions = {
                    content: labelText,
                    boxStyle: {
                        border: "none",
                        textAlign: "center",
                        fontSize: "10pt",
                        width: "50px"
                    },
                    disableAutoPan: true,
                    pixelOffset: new google.maps.Size(-25, -5),
                    position: latlng,
                    closeBoxURL: "",
                    isHidden: false,
                    pane: "floatPane",
                    enableEventPropagation: true
                };

                // Add circle overlay and bind to marker
                var circle = new google.maps.Circle({
                    map: map,
                    radius: 800, 
                    fillColor: fill_color_val,
                    strokeColor: '#69DAED',
                    strokeWeight: 2,
                    fillOpacity: 1,
                });

                var marker = new google.maps.Marker({
                    position: latlng,
                    title: datadetail[i].Author,
                    draggable: false,
                    map: map
                });
                marker.setVisible(false);

                circle.bindTo('center', marker, 'position');

                google.maps.event.addListener(circle, 'click', getInfoCallback(map, latlng));

                myOptions.content = datadetail[i].Count;
                var ibLabel = new InfoBox(myOptions);
                ibLabel.open(map);
                gmarkers.push(circle); 
                gmlist.push(marker); 
            }

        }
    }
        function getInfoCallback(map, latlng) {
            return function () {
                map.setZoom(15);
                map.setCenter(latlng);
            };
        }

        var data = [ ... ]; // Data Array

        var datadetail = [ ... ]; // Detail Data Array

        function ClearMapMaker() {
            console.log(gmlist);

            for (i = 0; i < gmlist.length; i++) {

                gmlist[i].setMap(null);
            }
            gmlist = [];
            console.log(gmarkers);
            for (i = 0; i < gmarkers.length; i++) {
                gmarkers[i].setOptions({ fillOpacity: 0, strokeOpacity: 0 });
                gmarkers[i].setMap(null);
            }
        }
</script>

Answer №1

 var markers = [];
    var list = [];
    var infoList=[];
    var fill_color_val = '#3888ff';
    var label_value = "1";
    var zoomLevel = 0;
    $(function () {
        function initialize_map() {
            var mapProperties = {
                minZoom: 11,
                maxZoom: 20,
                center: new google.maps.LatLng(16.7803886, 96.1844148),
                zoom: 12,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map"), mapProperties);
            bindMarkerOnMap("level_0");
        }

        initialize_map();

        map.addListener('zoom_changed', function () {
            zoomLevel = map.getZoom();
            if (zoomLevel <= 12) {
                ClearMapMarkers();
                ClearInfoBoxes();
                console.log(map.getZoom());
                bindMarkerOnMap("level_0");
            } else if (zoomLevel >= 13 && zoomLevel <15) {
                console.log("level_1 fired + " + zoomLevel);
                ClearMapMarkers();
                ClearInfoBoxes();
                
                bindMarkerOnMap("level_1");
            }else if (zoomLevel >= 15) {
                bindMarkerOnMap("level_2");
            }
        });

    });

    function bindMarkerOnMap(level) {
        console.log(level);
        if (level == "level_0") {
            console.log("level_0 binding");
            for (var i = 0; i < data.length; i++) {
                var location = new google.maps.LatLng(data[i].Lat, data[i].Long);

                var options = {
                    content: label_value,
                    boxStyle: {
                        border: "none",
                        textAlign: "center",
                        fontSize: "10pt",
                        width: "50px"
                    },
                    disableAutoPan: true,
                    pixelOffset: new google.maps.Size(-25, -5),
                    position: location,
                    closeBoxURL: "",
                    isHidden: false,
                    pane: "floatPane",
                    enableEventPropagation: true
                };

                
                var circle = new google.maps.Circle({
                    map: map,
                    radius: 1600, 
                    fillColor: fill_color_val,
                    strokeColor: '#69DAED',
                    strokeWeight: 2,
                    fillOpacity: 1,
                });

                var marker = new google.maps.Marker({
                    position: location,
                    title: data[i].Author,
                    draggable: false,
                    map: map
                });
                marker.setVisible(false);

                circle.bindTo('center', marker, 'position');

                google.maps.event.addListener(circle, 'click', getInfoCallback(map, location));

                options.content = data[i].Count;
                var infoLabel = new InfoBox(options);
                infoLabel.open(map);
                markers.push(circle);
                list.push(marker);
            }
        } else if (level == "level_1") {
            console.log("level_1 binding");
            for (var i = 0; i < datadetail.length; i++) {
                var location = new google.maps.LatLng(datadetail[i].Lat, datadetail[i].Long);

                var options = {
                    content: label_value,
                    boxStyle: {
                        border: "none",
                        textAlign: "center",
                        fontSize: "10pt",
                        width: "50px"
                    },
                    disableAutoPan: true,
                    pixelOffset: new google.maps.Size(-25, -5),
                    position: location,
                    closeBoxURL: "",
                    isHidden: false,
                    pane: "floatPane",
                    enableEventPropagation: true
                };

               
                var circle = new google.maps.Circle({
                    map: map,
                    radius: 800, 
                    fillColor: fill_color_val,
                    strokeColor: '#69DAED',
                    strokeWeight: 2,
                    fillOpacity: 1,
                });

                var marker = new google.maps.Marker({
                    position: location,
                    title: datadetail[i].Author,
                    draggable: false,
                    map: map
                });
                marker.setVisible(false);

                circle.bindTo('center', marker, 'position');

                google.maps.event.addListener(circle, 'click', getInfoCallback(map, location));

                options.content = datadetail[i].Count;
                var infoLabel = new InfoBox(options);
                infobox.open(map);
   
                infoList.push(infoLabel);
                markers.push(circle); // For Circles
                list.push(marker); // For Marker
                
            }

        }
    }
        function getInfoCallback(map, location) {
            return function () {
                map.setZoom(15);
                map.setCenter(location);
            };
        }

       //data array
      
       
      
 

            
//Clears markers on the map
function ClearMapMarkers() {
console.log(list);

for (i = 0; i < list.length; i++) {

list[i].setMap(null);
}
list = [];
   console.log(markers);
for (i = 0; i < markers.length; i++) {
markers[i].setOptions({ fillOpacity: 0, strokeOpacity: 0 });
markers[i].setMap(null);
}
}
//Clears Infoboxes currently open on the map
function ClearInfoBoxes() {
console.log(infoList);

for (i = 0; i < infoList.length; i++) {

infoList[i].close();
}
}
</script>

This method may be worth a shot.

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

What could be the reason for the malfunction of jQuery's show() function?

Using jQuery, I have implemented a functionality to hide a div using the hide() method. However, upon clicking a link, the div is supposed to show but unexpectedly disappears after appearing briefly. HTML Code Snippet <div id="introContent"> & ...

Issues with javascript functionality in Internet Explorer version 9 and higher

Currently, there is a flash music player (audioplay) embedded on a website. Despite personal preferences against having music on websites, it was requested by the client. The functionality in question involves using JavaScript to trigger "stop" and "play," ...

Angular code is malfunctioning and not delivering the expected results

I currently have setup the code below: var videoControllers = angular.module('videoControllers', []); videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){ $http.get('http://localho ...

Developing a Chessboard Using JavaScript

Seeking help with a Javascript chessboard project. I have successfully created the board itself, but facing difficulty assigning appropriate classes (black or white) to each square. Managed to assign classes for the first row, struggling with the remainin ...

Working with extensive amounts of HTML in JavaScript

Is there a way to dynamically load large amounts of HTML content in JavaScript? I'm struggling to figure out how to insert all the HTML content into the designated space within the JavaScript code. If anyone knows a different approach or solution, ple ...

Here are the steps to calculate the duration between two dates in the specified format:

let d1 = new Date("05/20/2022 09:28:15") let d2 = new Date("05/24/2022 12:38:25") Can someone help me calculate the difference between these two dates? ...

Display an image when the cursor hovers over a text

I'm attempting to display an image when hovering over specific text. The image should not replace the text, but appear in a different location. The concept is as follows: When hovering over the word "Google", the Google logo should appear in the red ...

Using a semicolon at the end of the line is considered a favorable practice when writing ES6 code in Babel

After browsing through various tutorials on the internet that utilize redux and react, I came across a common trend of omitting semicolons in ES6 code when using Babel. For instance, some examples neglect to include semicolons at the end of import or expo ...

How to set a cookie within an iframe while using Safari browser

Despite searching extensively on Stackoverflow and various other sources, I have not been able to find a solution that works for my specific case. The scenario is as follows: we have an application on domain A that we do not have control over, and an appl ...

Where is the optimal location for placing a JavaScript listening function within an Angular component?

Summary: Incorporating a BioDigital HumanAPI anatomical model into my Angular 5 application using an iFrame. The initialization of the API object is as follows: this.human = new HumanAPI(iFrameSrc); An important API function human.on(...) registers clic ...

The value of req.headers('Authorization') has not been defined

I'm experiencing difficulty with my code as the token is coming back as undefined. Here is the frontend section: export const fetchUser = async (token: any) => { const res = await axios.post('/user/getuser', { headers ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Exploring the capabilities of multiple nested controllers in AngularJS

I am facing a challenge that I haven't been able to find a solution for online. My search form includes multiple instances of a common controller used for typeahead/autocomplete searches. Each controller is set up with different parameters for search ...

Selenium allows the liberation of a webpage from suspension

I'm facing an issue with resolving the suspension of a website as shown in the image below. My goal is to access a ticket selling website every 0.1 seconds, but if it's busy, I want it to wait for 10 seconds before trying again. Visit http://bu ...

What is the best way to stop event bubbling in react-router-dom when using the <Link> component?

Hey there! I have a situation that I need help with. I tried putting the Link around the whole post so that I could prevent bubbling for individual buttons, but for some reason stopPropagation() is not working as intended. Following advice from another s ...

Ensuring the accuracy of user input

Can someone assist me with comparing two dates in JSP? I need validation that alerts the user when a future date is entered. The start date or end date should not be in the future. The date format is 12-5-2011 10:51:49. Any help would be greatly apprecia ...

What is the method for obtaining the viewModel in a Knockout component?

I need to prepopulate a knockout component when the document is ready. This is the code I have written: function Finding(id, trigger) { var self = this; self.id = ko.observable(id); self.trigger = ko.observable(trigger); } function FindingVi ...

Implementing image-based autocomplete in a search bar within an MVC framework

Seeking assistance to implement a unique feature for my MVC application. I aim to create a search box that suggests images based on user input rather than text. The functionality involves matching the user's input with the "Title" property in an Ent ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...