[GIS] how to remove previous marker automatically before adding new marker

angularjscordovaleaflet

I am using ui-leaflet on my ionic 1 mobile app which is the same as angular-leaflet-directive shown in the plunker link.

I am getting the user location and adding it to the marker and circle in the map, the issue i am having is that has the user moves their location is updated and therefore adding a new marking which then spans the maps which is not what I want.
What I am trying to achieve is that has a new marker is added or before a new marker is added, It should remove the old marker. How can I do this please? Below is my code and what I have tried

var app = angular.module("myApp", ['leaflet-directive'])

.controller('myCtrl', myCtrl);
myCtrl.$inject = ['$scope', 'leafletData'];

function myCtrl($scope, leafletData) {
  var location = {
    lat: -33.8830,
    lng: 151.2166
  };

  var mainMarker = {
    lat: location.lat,
    lng: location.lng,
    focus: true,
    draggable: false
  };

  var vm = angular.extend(this, {
    center: {
      lat: location.lat,
      lng: location.lng,
      zoom: 17
    },
    markers: {
      mainMarker: angular.copy(mainMarker)
    },
    defaults: {
      zoomControl: false
    },
    tiles: {
      url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
    }
  });

  function onLocationFound(e) {
    var radius = e.accuracy / 2;
    var marker;

    leafletData.getMap().then(function(map) {
      /* does not work in removing the old marker */

      if (marker) { // check
        map.removeControl(marker); // remove
      }

      var options = {
        icon: {
          icon: 'fa-certificate',
          prefix: 'fa',
          shape: 'square',
          markerColor: 'green'
        }
      };

      marker = L.marker(e.latlng).addTo(map);
      //.bindPopup("You are within " + radius + " meters from this point").openPopup();

      L.circle(e.latlng, radius).addTo(map);


    });
  }

  function onLocationError(e) {
    alert(e.message, e.code);
  }

  leafletData.getMap().then(function(map) {
    L.easyButton({
      position: 'bottomright',
      states: [{
        icon: 'fa fa-location-arrow fa-lg',
        onClick: function(btn, map) {
          map.locate({
            setView: true,
            maxZoom: 16,
            watch: true,
            enableHighAccuracy: true
          });
          map.on('locationfound', onLocationFound); //see if it is possible to pass the map has a perimetrr
          map.on('locationerror ', onLocationError);
        }
      }]
    }).addTo(map);
  });
}

Best Answer

map.removeControl(marker); should be map.removeLayer(marker);

It never fires though because marker is undefined. I don't use Angular but it seems like you need to do something to have marker in scope. This may be the wrong approach in Angular, but this fiddle works and should get you in the right direction.