Javascript 删除googlemap api v3中的一个标记

Javascript 删除googlemap api v3中的一个标记,javascript,jquery,google-maps-api-3,Javascript,Jquery,Google Maps Api 3,当我用邮政编码搜索一个位置时,我用邮政编码将谷歌地图居中,并添加一个标记。当我进行新的搜索时,我会删除旧的标记 $('body').on('blur', '#CodePostalA', function(){ var zipcode = $('#CodePostalA').val(); var $this = $(this); var geocoder = new google.maps.Geocoder; g

当我用邮政编码搜索一个位置时,我用邮政编码将谷歌地图居中,并添加一个标记。当我进行新的搜索时,我会删除旧的标记

     $('body').on('blur', '#CodePostalA', function(){

        var zipcode = $('#CodePostalA').val();
        var $this = $(this);
        var geocoder = new google.maps.Geocoder;

            geocoder.geocode({'address': zipcode}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    map.setZoom(20);

                }

                if ($('#adresse').length > 0) {
                    newMarker = new google.maps.Marker({
                        position: results[0].geometry.location,
                        map: map,
                        icon: new google.maps.MarkerImage(
                            'images/marker-new.png',
                            null,
                            null,
                            null,
                            new google.maps.Size(36, 36)
                        ),
                        draggable: true,

                        animation: google.maps.Animation.DROP,
                    });



                    google.maps.event.addListener(newMarker, "mouseup", function(event) {
                        var latitude = this.position.lat();
                        var longitude = this.position.lng();


                        geocoder.geocode({'location': this.position}, function(results, status) {
                            if (status === google.maps.GeocoderStatus.OK) {
                                if (results[1]) {
                                    $('#adresse').val(results[0].formatted_address);
                                } else {
                                    console.log('Aucun résulat trouvé');
                                }
                            } else {
                                console.log('Echec géolocation: ' + status);
                            }
                        });
                    });

                }




            });



    });



    addMarkers(props, map);
}, 300);

使用变量跟踪标记,当需要删除时,使用
marker.setMap(null)
将其从映射中删除

删除所有引用后,旧标记对象将在后台被垃圾收集


你也可以考虑重新使用标记对象,而不是每次都做一个新的标记。在创建新标记之前请尝试此操作。我理解,但是当我在newMarker=new google.maps.Marker({})之前添加newMarker.setMap时,我的控制台中出现错误=>Uncaught TypeError:newMarker.setMap不是一个函数,为什么在创建标记之前调用setMap?