0

我不明白为什么使用 .setMat(null) 我无法删除地图中的标记。

代码如下:

<!DOCTYPE html>
<HTML>  <HEAD>
        <script type="text/javascript">
            var geocoder;
            var map;
            var lat_;
            var lng_;
            var contentString="";
            var infowindow = null;
            var markerNodes = null;

            function initialize() {
                geocoder = new google.maps.Geocoder();
                var latlng = new google.maps.LatLng(41.92, 12.93);
                var mapOptions = {
                  zoom: 6,
                  center: latlng,
                  mapTypeId: google.maps.MapTypeId.ROADMAP
                }
                map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            }

            function searchLocations() {
                var ind_r_g = document.getElementById("indirizzoR").value;
                var civ_r_g = document.getElementById("civicoR").value;
                var citta_r_g = document.getElementById("cittaR").value;
                var paese_r_g = document.getElementById("paeseR").value;
                if(civ_r_g != 0 || civ_r_g != ""){
                var address = ind_r_g + civ_r_g + ", " +  citta_r_g + ", " + paese_r_g;
                }
                else{
                var address = ind_r_g +  ", " +  citta_r_g + ", " + paese_r_g;
                }

                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({address: address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    searchLocationsNear(results[0].geometry.location);
                } else {
                    alert(address + ' not found');
                }
                });
            }

            function clearLocations() {
            if(markerNodes!=null){
                alert(markerNodes.length);
                for (var i = 0; i < markerNodes.length; i++) {
                    markers[i].setMap(null);
                }
                }
            }               


            function searchLocationsNear(center) {
                alert("beforeclearlocations");
                clearLocations();
                alert("afterclearlocations");
                var radius = document.getElementById('raggioR').value;
                var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
                infowindow = new google.maps.InfoWindow({content: contentString});

                downloadUrl(searchUrl, function(data) {
                    var xml = data.responseXML;
                    markerNodes = xml.documentElement.getElementsByTagName("marker");
                    for (var i = 0; i < markerNodes.length; i++) {

                        var name = markerNodes[i].getAttribute("name");
                        var address = markerNodes[i].getAttribute("address");
                        var point = new google.maps.LatLng(
                            parseFloat(markerNodes[i].getAttribute("lat")),
                            parseFloat(markerNodes[i].getAttribute("lng")));
                        var image = '/img/'+ name +'.png';

                    contentString = '<div id="content">'+
                '<h3 id="firstHeading" class="firstHeading">' + markerNodes[i].getAttribute("name")+ '</h3>'+
                '<div id="bodyContent"><u>Indirizzo</u>: ' + markerNodes[i].getAttribute("address_indirizzo")  +'<br><u>Citta</u>: '+ markerNodes[i].getAttribute("city")
                + '<br><u>Paese</u>: ' + markerNodes[i].getAttribute("country") + '<br><u>Prezzo Benzina</u>: ' + markerNodes[i].getAttribute("prezzoB") + ' (euro/litro)</div>' + 
                '<u>Prezzo Diesel</u>: ' + markerNodes[i].getAttribute("prezzoD") +
                ' (euro/litro)</div>'+
                '</div>';       

                        var marker = new google.maps.Marker({
                            id: i,
                            map: map,
                            icon: image,
                            position: point,
                            html: contentString
                        });
                        google.maps.event.addListener(marker, 'click', function() {
                            infowindow.setContent(this.html);
                            infowindow.open(map,this);
                        });
                    }
                });
            }   


            function downloadUrl(url, callback) {
                var request = window.ActiveXObject ?
                    new ActiveXObject('Microsoft.XMLHTTP') :
                    new XMLHttpRequest;

                request.onreadystatechange = function() {
                    if (request.readyState == 4) {
                        request.onreadystatechange = doNothing;
                        callback(request, request.status);
                    }
                };

                request.open('GET', url, true);
                request.send(null);
            }


            function doNothing() {}

            function check_form_r(){
                var check_i_r = document.getElementById("indirizzoR").value;
                var check_civ_r = document.getElementById("civicoR").value;
                var check_cit_r = document.getElementById("cittaR").value;
                var check_pa_r = document.getElementById("paeseR").value;           
                var check_ra_r = document.getElementById("raggioR").value;
                if( check_i_r == ""  || check_cit_r == ""  || check_pa_r == "" || check_ra_r== ""){
                    alert("Tutti i campi con asterisco sono obbligatori");
                }
                else{
                searchLocations();
                }
            }

    </script>
    </HEAD>
    <BODY onload="initialize();">
    <div  class="insertbox" style="center">
        <h5>CERCA I BENZINAI INTORNO A TE!</h5>
                    Indirizzo (*): <br/>
                    <input type="text" name="indirizzoR" id="indirizzoR"/> <br/>
                    Civico: <br/>
                    <input type="text" size="4" name="civicoR" id="civicoR"/> <br/>
                    Città (*): <br/>
                    <input type="text" name="cittaR" id="cittaR"/> <br/>
                    Paese (*): <br/>
                    <input type="text" name="paeseR" id="paeseR"/> <br/>
                    <label for="raggioR">Raggio di ricerca (*):</label><br/>
                    <select id="raggioR" name="raggioR">
                    <option value="" selected="selected">-- seleziona --</option>
                    <option value="2" id="raggio2">2 km</option>
                    <option value="5" id="raggio5">5 km</option>
                    <option value="10" id="raggio10">10 km</option>
                    </select><br/>
                    <input type="button" value="cerca"  onclick="check_form_r()"/>
                    <br/>
                    <br/>
                    (i campi con asterisco sono obbligatori)
    </div>
<div class="mapbox" id="map_canvas" style="width:700px; height:350px" ></div>   
</BODY>

代码中的重要一点是clearLocations()我不明白我必须在里面放什么才能删除之前放置的所有标记的功能。

4

1 回答 1

0

你来做这件事:

for (var i = 0; i < markerNodes.length; i++) {
                    markers[i].setMap(null);

那不应该是:

for (var i = 0; i < markerNodes.length; i++) {
                    markerNodes[i].setMap(null);

您的代码中没有调用数组markers(事实上,如果您在执行此操作时没有收到 JS 错误,我会感到很惊讶)。

但是我认为即使这对你也不起作用。markerNodes 似乎是地图上的项目数组。最好在初始化地图时创建一个空白数组,然后在添加时将每个标记推送到该数组。

这是代码相关部分的更新,请注意新的全局变量markers以及我们在创建标记时将它们推入其中的位置。这就是我们在clearLocations函数中使用的数组。

var geocoder;
var map;
var lat_;
var lng_;
var contentString="";
var infowindow = null;
var markerNodes = null;
var markers = [];

function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(41.92, 12.93);
    var mapOptions = {
      zoom: 6,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}

function clearLocations() {
    alert(markers.length);
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
}               

function searchLocationsNear(center) {
    alert("beforeclearlocations");
    clearLocations();
    alert("afterclearlocations");
    var radius = document.getElementById('raggioR').value;
    var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
    infowindow = new google.maps.InfoWindow({content: contentString});

    downloadUrl(searchUrl, function(data) {
        var xml = data.responseXML;
        markerNodes = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markerNodes.length; i++) {

            var name = markerNodes[i].getAttribute("name");
            var address = markerNodes[i].getAttribute("address");
            var point = new google.maps.LatLng(
                parseFloat(markerNodes[i].getAttribute("lat")),
                parseFloat(markerNodes[i].getAttribute("lng")));
            var image = '/img/'+ name +'.png';

        contentString = '<div id="content">'+
    '<h3 id="firstHeading" class="firstHeading">' + markerNodes[i].getAttribute("name")+ '</h3>'+
    '<div id="bodyContent"><u>Indirizzo</u>: ' + markerNodes[i].getAttribute("address_indirizzo")  +'<br><u>Citta</u>: '+ markerNodes[i].getAttribute("city")
    + '<br><u>Paese</u>: ' + markerNodes[i].getAttribute("country") + '<br><u>Prezzo Benzina</u>: ' + markerNodes[i].getAttribute("prezzoB") + ' (euro/litro)</div>' + 
    '<u>Prezzo Diesel</u>: ' + markerNodes[i].getAttribute("prezzoD") +
    ' (euro/litro)</div>'+
    '</div>';       

            var marker = new google.maps.Marker({
                id: i,
                map: map,
                icon: image,
                position: point,
                html: contentString
            });
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent(this.html);
                infowindow.open(map,this);
            });

            // add this marker to our array
            markers.push(marker);
        }
    });
}   
于 2013-02-12T16:22:56.073 回答