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 is the best way to change the format of a datetime?

While working with sailsjs(node.js), I have successfully retrieved all the data from a MySQL database and displayed it in a jtable. However, the date format is currently showing as YYYY-MM-DDTHH:mm:ss.000Z. I am looking to convert this format (YYYY-MM-DDT ...

Internet Explorer does not support the split function in JavaScript

I've been utilizing the split function to separate dates, but I encountered an issue where the code doesn't function properly in Internet Explorer, although it works fine in other browsers. The ul and li elements are dynamically generated. <! ...

Unable to retrieve button value with material-ui package

My task requires me to retrieve the value of a button, as it contains an ID essential for further steps. Initially, I used a standard button with Bootstrap styling and everything functioned correctly. <button value={row.vacationRequestID} c ...

Is it possible to import data into a script?

When working with Angular, I am attempting to: $scope.data = "<script> alert('hi'); </script>"; Unfortunately, this approach does not seem to be effective. I also experimented with adding ng-bind-html but did not achieve any success ...

Clicking on a Vuetify v-btn with the :href attribute set to download will open the XML file

I'm having trouble getting the v-btn to download an XML file instead of opening it in the browser. <v-btn :disabled="!exportUrl" block x-large height="100" color="primary" :href="exportUrl" download> ...

Exploring the dissimilarity among npm run dev and the parcel index.html

I have been using parcel index.html to set up a local development server, bundling, and hot module replacement. However, I recently learned that npm run dev can do something similar. This has left me wondering: What are the distinctions between the two me ...

There was an error: "Uncaught TypeError - onPageChange function is not defined for the DataGrid component in Material

I'm struggling to integrate a DataGrid component into my application. While the table renders correctly with the code provided, I encounter an error when clicking on the next page icon - react-dom.development.js:327 Uncaught TypeError: onPageChange is ...

In what way does ReactJS enable me to utilize constant functions before they are declared?

I'm intrigued by the concept of using a value before defining it in ReactJS. Let's explore this through an example: function CounterApp() { const [counter, setCounter] = useState(0); const increaseValueTwice = () => { increaseValue() ...

Looking for a solution to my issue - my for loop is looping more times than it should

I am designing a confirm dialog using jQuery and Bootstrap. When the user clicks on 'Yes' or 'No', it should trigger an action, such as drawing two squares each time. The first time I click either button, it draws 2 squares. However, wi ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX ...

Having trouble getting gulp set up and running with npm?

I am currently in the process of setting up gulp using npm in order to execute my project. Based on my understanding, all I need to do is enter "npm install gulp" in the command line at the location of my project like this : https://i.stack.imgur.com/hPU ...

Showing a restricted number of rows in the JSP page

<table class="grid_alt" cellspacing="0" rules="all" border="1" id="id1" style="width:720px;border-collapse:collapse;"> <tbody> <tr align="left"> <th scope="col"><%=partner %></th><th scope="col"><%=item %>< ...

Adjusting the Pace of a CSS Marquee

My CSS marquee effect is working perfectly, but I am having trouble with the speed. The issue arises when the text length varies - shorter text takes longer to scroll while longer text scrolls quickly. This inconsistency is due to the animation duration an ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

Dealing with child elements in isomorphic React applications: a comprehensive guide

Looking at my server code, here is how it appears: var data = { scripts: scripts, children:[<Comp1 />, <Comp2 />, <Comp3 />] }; // keeping smaller for easier example than reality var markup = ''; markup += '<scrip ...

Transferring variables from the $(document).ready(function(){}) to the $(window).load(function(){} allows for seamless and

Just think about if I successfully create percent_pass at the time of document.ready, how can I transfer that variable to window.load? $(document).ready(function() { jQuery(function() { var ques_count = $('.question-body').length; va ...

Create an Android application using Node.js

While developing my mobile application, I am utilizing html5 with node.js to create a chat box for users connected on the same wireless network. However, I encounter an issue when coding on my desktop using node.js software. How can I overcome this challen ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

Guide on incorporating jQuery library files into existing application code with the npm command

Recently, I used a node JS yo ko command to create a single-page application using Knockout-JS. Following that, I proceeded to install jquery packages using the command npm install jquery The installation was successful. However, my current goal is to in ...

Ways to deactivate the Bootstrap collapse feature

In my accordion FAQs, I am facing an issue where Question 1 is automatically opened when the page loads. Additionally, when I click on Question 2, it closes instead of staying open. I would like to address these problems and make sure that each question st ...