单击第二次清除Google地图

时间:2018-08-19 07:46:15

标签: javascript google-maps

我正在将google map用于我的项目。当用户单击地图时,我会显示一个标记。如何清除地图并再次单击显示另一个标记?

                function myMap() {
                    var mapCanvas = document.getElementById("map");
                    var myCenter = new google.maps.LatLng(32.1788385, 54.5177581);
                    var mapOptions = {center: myCenter, zoom: 5};
                    var map = new google.maps.Map(mapCanvas, mapOptions);
                    google.maps.event.addListener(map, 'click', function (event) {
                        placeMarker(map, event.latLng);
                    });
                }

                function placeMarker(map, location) {
                    var marker = new google.maps.Marker({
                        position: location,
                        map: map
                    });
                }

1 个答案:

答案 0 :(得分:0)

您需要将标记的引用保存在全局变量中。您还需要检查marker的类型或将其包装在try-catch语句中。

const mapCanvas = document.getElementById("map");
var marker;

function initMap(){

    var myCenter = new google.maps.LatLng(32.1788385, 54.5177581);
    var mapOptions = {center: myCenter, zoom: 5};

    var map = new google.maps.Map(mapCanvas, mapOptions);

    google.maps.event.addListener(map, 'click', function (event) {
        placeMarker(map, event.latLng);
    });
}

function placeMarker(map, location) {

    // Remove the previous marker
    try {
        marker.setMap(null)
    } catch (e) {}

    // Update the marker
    marker = new google.maps.Marker({
        position: location,
        map: map
    });

}

Fiddle