GeoMaps GeoMaps - 4 months ago 29
Javascript Question

Deleting drawn polygons in Google Maps

I'm working on a project and I ended up using Fusion Tables. However, I want to deal with Event Listeners. For this reason, I'm using a technology called JSONP.

In the example I showed below (fiddle), It has both fusion table (Red Fill) and a JSONP (No Fill with Black stroke) working together, just to picture what I'm trying to achieve.

Each time the user presses the button "GO" I want to draw all the polygons returned by the JSONP request, with its attributes

This first example re-draws the polygons but only one.

The second Exampledraws all the polygons but doesn't delete the old ones. (I tried to use

Regions.setMap(null);
e
delete Regions;
and didn't work)

So, what I want is a suggestion how I could only draw in the map the polygons the user queried maintaining its attributes.

code snippet:



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);

}

function drawMap(data) {

var rows = data['rows'];
for (var i in rows) {
var newCoordinates = [];

newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);

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);
}

}

//access the lat and long for each node and return a 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>




Answer

My suggestion would be to keep references to the polygons in an array (ie.e gmarkers), then set the map property of all the polygons to null (to hide them) before creating any 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);
}

proof of concept fiddle

code snippet:

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 a 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>

Comments