Removing all hand-drawn shapes on Google Maps

I am currently working on a project that involves using Fusion Tables, but I want to incorporate Event Listeners as well. To achieve this, I am utilizing JSONP technology.

In the example provided below (in the fiddle link), you can see both the fusion table (marked with red fill) and a JSONP element (marked with no fill and black stroke) working in unison to illustrate my objective.

Each time the user clicks the "GO" button, I aim to draw all the polygons returned by the JSONP request along with their attributes.

This initial example redraws the polygons individually.

The second example draws all the polygons but fails to remove the old ones. (I attempted using Regions.setMap(null); and delete Regions; without success)

Therefore, I am seeking suggestions on how to only display the queried polygons on the map while maintaining their attributes.

Code Snippet:

html,
        body {
          height: 100%;
          margin: 0;
          padding: 0;
        }
        #map {
          height: 90%;
        }
<script>
            // JavaScript code here
           </script>

Answer №1

To improve the performance, it is recommended to store references to the polygons in an array (e.g. gmarkers) and then hide them by setting the map property of all the polygons to null before creating new ones.

for (var i in rows) {
    var newCoordinates = [];
    newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
    var Regions = new google.maps.Polygon({
        paths: newCoordinates,
        strokeColor: '#000000',
        strokeOpacity: 1,
        strokeWeight: 2,
        fillOpacity: 0,
        //retrieve all the Fusion Table information for each row
        row: (function(index){
                    var row={};
                        for(var j=0;j<data['rows'][index].length;++j){
                        row[data.columns[j]]=data['rows'][index][j];
                    }
                    return row;
                })(i)
    });
    //Working Mouseover event
    google.maps.event.addListener(Regions, 'mouseover', function() {
        this.setOptions({strokeWeight: 3});
    });
    //Working Mouseout event
    google.maps.event.addListener(Regions, 'mouseout', function() {
        this.setOptions({strokeWeight: 1});
    });
    // Working click event
    google.maps.event.addListener(Regions, 'click', function (event) {
        var Content = this.row['Sigla_Muni'];
        infowindow.setPosition(event.latLng);
        infowindow.setContent(Content);
        infowindow.open(map);
    });

    Regions.setMap(map);
    gpolygons.push(Regions);
}

Check out the proof of concept fiddle

Snippet of CSS code:

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 90%;
}
<script>
  function initMap() { //http://devfestmtm.appspot.com/#1

      var mapProp = {
        zoom: 9,
        center: {
          lat: -18.92990560776172,
          lng: -43.4406814550781
        },
      };
      map = new google.maps.Map(document.getElementById('map'), mapProp);

      //Instantiate the InfoWindow
      infowindow = new google.maps.InfoWindow({
        maxWidth: 350,
        //pixelOffset: new google.maps.Size(0,5)
      });

      //************* Loading Fusion Table

      var tableId = '1WMlA-1ik05epxVKu0l5Pgyi5WtmCg1W3-akwE4Ps';
      var locationColumn = 'geometry';
      var Regioes_AOI_FusionTable = new google.maps.FusionTablesLayer({
        query: {
          select: locationColumn,
          from: tableId
        },
        suppressInfoWindows: true,
        map: map,
      });

      google.maps.event.addDomListener(document.getElementById('ButtonFilter'), 'click', function() {
        UpdateFusionTable(Regioes_AOI_FusionTable, tableId, locationColumn);
      });
      
    } // End Map


  function UpdateFusionTable(Regioes_AOI_FusionTable, tableId, locationColumn) {
    var queryGenerated = document.getElementById('Regions').value;

    Regioes_AOI_FusionTable.setOptions({
      query: {
        select: locationColumn,
        from: tableId,
        where: queryGenerated
      }
    });

    // Initialize JSONP request
    var script = document.createElement('script');
    var url = ['https://www.googleapis.com/fusiontables/v2/query?'];
    url.push('sql=');
    var query = 'SELECT * FROM ' + tableId + " WHERE " + queryGenerated;
    var encodedQuery = encodeURIComponent(query);
    url.push(encodedQuery);
    url.push('&callback=drawMap'); //Calls the drawMap function
    url.push('&key=AIzaSyCoC9A3WgFneccRufbysInygnWrhCie-T0');
    script.src = url.join('');
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(script);

  }

  var gpolygons = [];

  function drawMap(data) {
    for (var i = 0; i < gpolygons.length; i++) {
      gpolygons[i].setMap(null);
    }
    var rows = data['rows'];
    for (var i in rows) {
      var newCoordinates = [];
      newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
      var Regions = new google.maps.Polygon({
        paths: newCoordinates,
        strokeColor: '#000000',
        strokeOpacity: 1,
        strokeWeight: 2,
        fillOpacity: 0,
        //retrieve all the Fusion Table information for each row
        row: (function(index) {
          var row = {};
          for (var j = 0; j < data['rows'][index].length; ++j) {
            row[data.columns[j]] = data['rows'][index][j];
          }
          return row;
        })(i)
      });

      //Working Mouseover event
      google.maps.event.addListener(Regions, 'mouseover', function() {
        this.setOptions({
          strokeWeight: 3
        });
      });

      //Working Mouseout event
      google.maps.event.addListener(Regions, 'mouseout', function() {
        this.setOptions({
          strokeWeight: 1
        });
      });

      // Working click event
      google.maps.event.addListener(Regions, 'click', function(event) {
        var Content = this.row['Sigla_Muni'];
        infowindow.setPosition(event.latLng);
        infowindow.setContent(Content);
        infowindow.open(map);
      });

      Regions.setMap(map);
      gpolygons.push(Regions);
    }
  }

  //access the lat and long for each node and return an array containing those values, extracted from fusion table.
  function constructNewCoordinates(polygon) {
    var newCoordinates = [];
    var coordinates = polygon['coordinates'][0];
    for (var i in coordinates) {
      newCoordinates.push(
        // write the lat and long respectively
        new google.maps.LatLng(coordinates[i][1], coordinates[i][0]));
    }
    return newCoordinates;
  }
</script>
<div>
  <select id="Regions">
    <br>
    <option value="Sigla_Muni = 'CMD'">CMD</option>
    <option value="Sigla_Muni = 'AM'">AM</option>
    <option value="Sigla_Muni = 'DJ'">DJ</option>
  </select>


  <button type="button" id="ButtonFilter">Go!</button>
</div>

<div id="map"></div>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBFYwb6-B6u2cs5oknTRwtfBng2kgdDMgk&callback=initMap">
</script>

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

Problems with the functionality of the remote feature in Twitter Bootstrap Modal

Utilizing Twitter Bootstrap, I aim to retrieve HTML from another page and inject it into the modal on my current page. This led me to create a JavaScript function to facilitate this process. Within my 'index.php' file, I include the following: ...

Using the jqueryRotate plugin to rotate an image by 90 degrees

Is there a way to rotate images on a webpage using the JQueryRotate script? I have 10 images that I want to be able to rotate when clicked, but I'm not sure how to implement it. Any assistance would be welcomed. This is the HTML code for the images: ...

Compact looped slideshow

Currently in the process of designing a website and looking to incorporate a unique photo gallery feature. The concept is as follows: The photo gallery will be displayed in a rectangular/box shape. There are a total of 10 photos, with only 7 initially vis ...

Adjust the scroll position when the height of a div is modified

Imagine we have a large div A with a height value and below it are other divs B, C, and more. If the user is viewing divs B or C, and A reduces its height by half, the scrolling position will remain the same. However, divs B and C will move up by that amo ...

Ensure all <li> tags within a HTML document exhibit consistent jquery mousedown and hover effects, abstaining from the assignment of unique IDs to each

I understand that this approach might not be correct, but I wanted to create a simulation of what I am trying to achieve. Is there a way for each <li> element within a specific <ul class="myul"> to have separate mousedown, mouseout, hover effe ...

Multiple clicks causing the button to increment excessively and fire repeatedly

Currently, I am working on a web application that includes a deploy button in one section. When this button is clicked, a modal pops up with two additional buttons, one for confirmation and the other for cancelation. The issue I am facing is that when I c ...

Tips for modifying HTML elements and navigating to a different webpage

As I delve into the world of front-end web development, I decided to challenge myself with a little exercise by creating a basic HTML form. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ...

Handling CORS in Vue.js applications

As a newcomer to Vue, I am currently grappling with a CORS issue in my application. During development at http://localhost:8080/, sending a request to , I was able to resolve the CORS problem using the following code snippet: vue.config.js module.exports ...

Transform your data visualization with Highcharts enhanced with the stylish appearance of DHTML

I am currently using a dhtmlx menu with my charts, specifically the legendItemClick event. It worked perfectly when I was using highcharts 3.0.1. However, after upgrading to version 4.1.7, the function legendMenu_<?=$id?>.showContextMenu(x,y) in the ...

Extract data from Markit On Demand API using JavaScript and AJAX

I'm struggling to properly parse the response from the API. While I can retrieve the entire response, I am a bit lost on how to effectively parse it. Below is my code snippet: <!DOCTYPE> <html> <head> <style> img ...

I need assistance with incorporating a datepicker feature using jQuery UI

Can someone please assist me? I am trying to incorporate a datepicker (Jquery UI) and add an additional function in the script for counting, but my understanding of jquery is limited. (My English skills are also lacking, apologies in advance) I would dee ...

Most effective method for integrating ajax URLs and browser history in a unique Joomla component

I have been given the task of enhancing the search functionality of a custom Joomla component that is solely operated through AJAX. Currently, the search does not handle URL/query strings, preventing users from using the browser back button to return to pr ...

Internet Explorer has been known to remove option tags that are added dynamically through

I've come across a code snippet that works perfectly in all browsers except IE. Here it is: var array = eval( '(' + xmlHttp.responseText + ')' ); var html = ''; for(var key in array) { html += '<option value ...

What is the reason behind the lack of preservation of object state when using Promises?

Here is a code snippet to consider: class ClientWrapper { private client: Client; constructor() { this.client = new Client(); } async connect() : Promise<void> { return this.client.connect(); } async isConne ...

Flickering transitions in Phonegap and jQuery Mobile pages

As a beginner in Phonegap/jQuery Mobile, I have encountered a frustrating issue of a white screen appearing during page transitions. Despite trying various solutions found online, such as using -webkit-backface-visibility:hidden;, the problem persists. I ...

Vanilla JS causing event to fire repeatedly

My code is written in Vanilla JS and I've encountered an issue with dynamically generated content. Each click on the dynamic content returns a different value than expected: First click: 1 Second click: 3 Third click: 6 Fourth click: 10 But it sh ...

Discovering the geographical location of all users using Node.js: A step-by-step guide

My current task involves determining the geoip location of users. I have implemented a code that stores the user's address in the database and then displays the geoip location accordingly. However, if a user changes their location and logs in from a d ...

"Utilizing the ajaxcontroltoolkit CascadingDropDown feature to trigger a method once the control

On my webpage, I am using a CascadingDropDown control and I am looking to trigger some jQuery actions once the dropdown is populated. As per the guidance provided in the documentation, there is an event called (populated) that can be used for this purpose. ...

Can Vue/JavaScript code be transmitted within an object to a different component?

The scenario involves a parent and child Vue components. In this setup, the child component transmits data to the parent component via a simple object emitted using the emit method. Data in the child component: const Steps [ { sequenc ...

Ways to clear the time attribute from an ISO DateTime in date format

How can I remove the time attribute from a date in the format 2016-05-24T05:07:57.756Z and set it to something like 2016-05-25T00:00:00.000Z? Any assistance would be greatly appreciated. ...