Search code examples
javascriptjquerygoogle-mapsgoogle-maps-api-3gmaps.js

gmaps.js | Remove old marker when a new marker is added


I am trying to create a location input field where in a user will select a location. So there should be only one marker present on the map.

My current code adds a marker on click:

    var map = new GMaps({
        div: '#m_gmap_2',
        zoom: 16,
        lat: -12.043333,
        lng: -77.028333,
        click: function(e) {
                     var lat = e.latLng.lat();
                     var lng = e.latLng.lng();
                     map.addMarker({
                                lat: lat,
                                lng: lng,
                                title: 'College Location'
                     });
        },
    });

But I cannot figure how to remove previous marker within click() or addMarker() function.

How can I go about doing this?


Solution

  • Save the previous marker so you can remove it when you add a new one. For example:

    var marker;
    var map = new GMaps({
        div: '#m_gmap_2',
        zoom: 16,
        lat: -12.043333,
        lng: -77.028333,
        click: function(e) {
            if( marker ) marker.setMap( null );
            var lat = e.latLng.lat();
            var lng = e.latLng.lng();
            marker = map.addMarker({
                lat: lat,
                lng: lng,
                title: 'College Location'
            });
        },
    });