简体   繁体   中英

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?

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'
        });
    },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM