删除地图中的标记

时间:2013-02-11 15:47:37

标签: php javascript google-maps marker

我无法理解为什么使用.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(),其中我不明白我必须放入什么来删除之前放置的所有标记。

1 个答案:

答案 0 :(得分: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);
        }
    });
}