How to delete markers (web based)

I have both /maps-web.min.js and services-web.min.js included,
I call this function to create a route and a new route, it did generate a new route, the problem is that i don’t know how to detect and delete the existing markers. marker.remove() is not working. Thanks in advance…

var createRoute = function(){

        if (map.getLayer("route")) {

        if (map.getSource("route")) {

        var lat1 = document.getElementById('lat1').value;
        var long1 = document.getElementById('lng1').value;
        var lat2 = document.getElementById('lat2').value;
        var long2 =  document.getElementById('lng2').value;

         marker1 = new tt.Marker().setLngLat([long1,lat1]).addTo(map);
         marker2 = new tt.Marker().setLngLat([long2,lat2]).addTo(map);

        var routeOptions = {
            key: API_KEY,
            locations: [],

          key: API_KEY,
          locations: long1 + ',' + lat1 +':'+ long2 +',' + lat2,
        .then(function(response) {
            var geojson = response.toGeoJson();
                'id': 'route',
                'type': 'line',
                'source': {
                    'type': 'geojson',
                    'data': geojson
                'paint': {
                    'line-color': '#0DEC05',
                    'line-width': 8
            var bounds = new tt.LngLatBounds();
            geojson.features[0].geometry.coordinates.forEach(function(point) {
            map.fitBounds(bounds, {padding: 20});

You have to keep references to markers created previously.
It can be for example an array. And when you want to remove them you just call remove() of each marker in an array.


I referenced marker1 and try to remove it before, but it seem to not be working. I tried it again today and it somehow works, not sure why. Thanks for enlightened me

hi! by any chance can you post the syntax used to solve this?