Search code examples
javascriptgoogle-mapsgmaps.js

gmaps.js - Drawing a Polygon


I am using gmaps.js and I can draw Polygons using this code

var paths = [];
function drawPoly(p1, p2) {
  paths.push([p1, p2]);
  console.log(paths);

  oldPolygon = null;

  map.drawPolygon({
      paths: paths,
      strokeColor: '#432070',
      strokeOpacity: 1,
      strokeWeight: 3,
      fillColor: '#432070',
      fillOpacity: 0.6
    });
}

But my problem is that they are overlapping each other resulting to this,enter image description here

My question is how do I remove the overlapping Polygons(Old Polygons) so that the remaining Polygon will be the last generated one. I hope I explained it well. Thanks.


Solution

  • The fix to my issue was to use the map.removePolygon method:

    var paths = [];
    var oldPolygon;
    function drawPoly(p1, p2) {
        paths.push([p1, p2]);
        console.log(paths);
    
        polygons = map.drawPolygon({
           paths: paths,
           strokeColor: '#432070',
           strokeOpacity: 1,
           strokeWeight: 3,
           fillColor: '#432070',
           fillOpacity: 0.6
        });
    
        // remove old one if exists.
        if(oldPolygon != null){
            map.removePolygon(oldPolygon);
        }
    
        // ... and save a reference to the new polygon for next time around.
        oldPolygon = polygons;
    }