Search code examples
javascriptgoogle-maps-api-3jsfiddle

Delete Polygon when creating a new one


I have a small google map https://jsfiddle.net/deMischa/fkLm5zg9/8/. If you click on it, a marker will be placed and a circle will be drawn around that marker.

If you click again, the marker is deleted and a new one is placed. That works fine.

function addMarker(location,blue) {  
  deleteMarkers();

  var marker = new google.maps.Marker({  
    position: location,  
    map: map,
    draggable: true
  });  
  markers.push(marker);  
  window.position = markers[0].position;

  addCircle();
}  

My problem is that I can't do the same thing with the polygon/circle.

I know that I can delete a polygon with

function deleteCircle() { 
  blue.setMap(null);
} 

And if I call that function from a button click, it's working. But I want this to be called from the function, that creates a new marker/circle. And here it is not working

function addMarker(location,blue) {  
  deleteMarkers();
  deleteCircle(); LIKE THE MARKERS, THE CIRCLES SHOULD BE DELETED HERE

  ...
}  

There is the following error in console

Uncaught TypeError: Cannot read properties of null (reading 'setMap')

Do you guys have any idea? I uploaded the whole script to https://jsfiddle.net/deMischa/fkLm5zg9/8/ so it might be easy to debug.


Solution

  • When I uncomment out the deleteCircle call, I get the following javascript error: Uncaught ReferenceError: blue is not defined, because blue is not defined until you have called the addCircle function for the first time.

    Duplicate/related questions:

    1. how to remove previous circle from the map?
    2. How to remove previous circle automatically before adding new circle in Google map

    Suggestion: You declare circle in the global scope but don't use it.

    1. change blue to circle.
    // Adds a circle to the position of the marker. 
    function addCircle() {
      circle = new google.maps.Polygon({
        paths: [drawCircle(new google.maps.LatLng(position), 0.1, 1)],
        strokeColor: "#0000FF",
        strokeOpacity: 0.5,
        strokeWeight: 2,
        fillColor: "white",
        fillOpacity: 0.15
      });
      circle.setMap(map);
    }
    
    1. check to see if the circle exists, then hide/delete it if it exists.
    // Delete the circle 
    function deleteCircle() { 
      if (circle && circle.setMap) 
        circle.setMap(null);
    }  
    

    proof of concept fiddle

    code snippet:

    var map = null;
    var circle = null;
    var bounds = null;
    var markerPosition = null;
    var markers = [];
    var position = new google.maps.LatLng(50.2275, 7.4885);
    
    function initialize() {
      var myOptions = {
        zoom: 15,
        center: position,
        mapTypeControl: false,
        navigationControl: true,
        mapTypeId: google.maps.MapTypeId.HYBRID
      }
    
      map = new google.maps.Map(document.getElementById("map"), myOptions);
      bounds = new google.maps.LatLngBounds();
    
      // This event listener will call addMarker() when the map is clicked.  
      map.addListener('click', function(event) {
        addMarker(event.latLng);
      });
    }
    
    
    // Adds a circle to the position of the marker. 
    function addCircle() {
      circle = new google.maps.Polygon({
        paths: [drawCircle(new google.maps.LatLng(position), 0.1, 1)],
        strokeColor: "#0000FF",
        strokeOpacity: 0.5,
        strokeWeight: 2,
        fillColor: "white",
        fillOpacity: 0.15
      });
      circle.setMap(map);
    }
    
    // Delete the circle 
    function deleteCircle() {
      if (circle && circle.setMap)
        circle.setMap(null);
    }
    
    
    // Adds a marker to the map and push to the array.  
    function addMarker(location) {
      deleteMarkers();
      deleteCircle(); //LIKE THE MARKERS, THE CIRCLES SHOULD BE DELETED HERE
    
      var marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable: true
      });
      markers.push(marker);
      window.position = markers[0].position;
    
      addCircle();
    }
    
    // Sets the map on all markers in the array.  
    function setMapOnAll(map) {
      for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
      }
    }
    
    // Removes the markers from the map, but keeps them in the array.  
    function clearMarkers() {
      setMapOnAll(null);
    }
    
    // Deletes all markers in the array by removing references to them.  
    function deleteMarkers() {
      clearMarkers();
      markers = [];
    }
    
    function drawCircle(point, radius, dir) {
      var d2r = Math.PI / 180; // degrees to radians 
      var r2d = 180 / Math.PI; // radians to degrees 
      var earthsradius = 3963; // 3963 is the radius of the earth in miles
    
      var points = 64;
    
      // find the radius in lat/lon 
      var rlat = (radius / earthsradius) * r2d;
      var rlng = rlat / Math.cos(point.lat() * d2r);
    
    
      var extp = new Array();
      if (dir == 1) {
        var start = 0;
        var end = points + 1
      } // one extra here makes sure we connect the
      else {
        var start = points + 1;
        var end = 0
      }
      for (var i = start;
        (dir == 1 ? i < end : i > end); i = i + dir) {
        var theta = Math.PI * (i / (points / 2));
        ey = point.lng() + (rlng * Math.cos(theta)); // center a + radius x * cos(theta) 
        ex = point.lat() + (rlat * Math.sin(theta)); // center b + radius y * sin(theta) 
        extp.push(new google.maps.LatLng(ex, ey));
        bounds.extend(extp[extp.length - 1]);
      }
      // alert(extp.length);
      return extp;
    }
    html,
    body {
      height: 100%;
      width: 100%;
      padding: 0px;
      margin: 0px;
    }
    
    .map {
      height: 80%;
      width: 100%;
    }
    <!doctype html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8">
      <script src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDCA7_eY2neZvNFOM8jhvjeTpuRS1-HkDU"></script>
      <script src="ol3gm.js"></script>
      <script src="math.js"></script>
      <title>Example</title>
    </head>
    
    <body onload="initialize()">
      <div id="map" class="map"></div>
      <br>
      <input onclick="deleteMarkers();" type=button value="Delete Markers">
      <input onclick="deleteCircle();" type=button value="Delete Circle">
    
    </body>
    
    </html>