Javascript 需要帮助清除地图上的标记-谷歌地图API V3

Javascript 需要帮助清除地图上的标记-谷歌地图API V3,javascript,google-maps-api-3,Javascript,Google Maps Api 3,我有一张地图正在做我需要它做的一切,但是我在设置一个合适的全局数组来存储我的标记,然后在从loadFromCitySelect()函数(通过下拉菜单)进行新选择时清除它时遇到了麻烦。我已尝试在load()函数调用之间清除全局\u gmarkers数组(即每次使用上面提到的citySelect函数选择新位置时)。我似乎不明白为什么它不起作用。如果有人能指出需要修复的内容,以便在每次loadFromCitySelect()调用之间清除标记,我将不胜感激 function loadFromCitySe

我有一张地图正在做我需要它做的一切,但是我在设置一个合适的全局数组来存储我的标记,然后在从loadFromCitySelect()函数(通过下拉菜单)进行新选择时清除它时遇到了麻烦。我已尝试在load()函数调用之间清除全局\u gmarkers数组(即每次使用上面提到的citySelect函数选择新位置时)。我似乎不明白为什么它不起作用。如果有人能指出需要修复的内容,以便在每次loadFromCitySelect()调用之间清除标记,我将不胜感激

function loadFromCitySelect(){
    //get selected city
    var city = getSelectedValue("city_select");
    load(LANGUAGE,city,0,-1);
}

function loadFromOfficeSelect(){
    //get selected city
    var city = getSelectedValue("city_select");
    var office = getSelectedValue("office_select");
    load(LANGUAGE,city,office,-1);
    //LANGUAGE was initially set when the page was first loaded
}

var Global_side_bar_html;
var Global_gmarkers;
var Global_htmls;
var Global_i;
var Global_points;
var Global_lasti;
var courtIcon = "http://maps.google.com/mapfiles/kml/pal2/icon10.png";
var iconONT = courtIcon;
    iconONT.image = courtIcon;
    iconONT.iconSize = new google.maps.Size(40, 40);
    iconONT.iconAnchor = new google.maps.Point(15, 15);
    iconONT.infoWindowAnchor = new google.maps.Point(17, 2);

// activate the InfoWindow and store it
var infoWindow = new google.maps.InfoWindow({
    size: new google.maps.Size(250,200) //not actually sure that this does anything?
});

/*    FUNCTIONS    */
/*******************/
function createInfoMarker(point, info, icon, name, num) {
    var marker = new google.maps.Marker({
        position: point,
        icon: courtIcon,
        map: map
    });
    // Global_gmarkers.push(marker);

    google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(Global_htmls[num]);
        infoWindow.open(map,marker);
        // map.setCenter(marker.getPosition());
    });

    google.maps.event.addListener(marker, 'click', function() {
        document.getElementById("printInfoBubble").innerHTML = info;
    });

    Global_gmarkers[Global_i] = marker;
    Global_htmls[Global_i] = info;
    Global_points[Global_i] = point;
    Global_side_bar_html += '<a id="'+Global_i+'" onmouseover="map_listings_highlight('+Global_i+');" onmouseout="map_listings_unhighlight('+Global_i+');" href="javascript:topListClick(' + Global_i + ')" class="listtag">' + name + '</a><br>';
    Global_i++;

    return marker;
} // end createInfoMarker

function topListClick(i){
    google.maps.event.trigger(Global_gmarkers[i], "click");
}

function init(){
    var mapOptions = {
            zoom: 12,
            center: new google.maps.LatLng(43.717272, -79.393044),
            scrollwheel: false,
            scaleControl: true,
            overviewMapControl: true,
            overviewMapControlOptions:{opened:true},
            mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    window.map = new google.maps.Map(document.getElementById("map"), mapOptions);

    //gather url string arguments
    LANGUAGE = getQueryVariable("lang"); //?lang=
    CITY = getQueryVariable("city"); //?city=
    COURT = getQueryVariable("court");
    PCODE = getQueryVariable("pcode");
    //if no url string arguments were passed, use the following as default
    if (CITY==""){
        CITY = 122; //Toronto as default
    }
    if (LANGUAGE==""){
        LANGUAGE = "en"; //EN by default
    }
    if (COURT==""){
        COURT = -1; //no court was passed
    }
    if (PCODE!=""){
        document.getElementById("postal_code").value = PCODE;
    }
    //load language variables
    initText(LANGUAGE);
    load(LANGUAGE,CITY,0,COURT);
}

function load(lang,city_id,office_id,court_id){
    Global_side_bar_html = "";
    Global_gmarkers = [];
    Global_htmls = [];
    Global_i = 0;
    Global_points = [];
    Global_lasti = -1;

    var xhr;
    try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
    catch (e) 
    {
    try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
        catch (e2) 
        { try { xhr = new XMLHttpRequest(); }
        catch (e3) { xhr = false; }
        }
    }

    xhr.onreadystatechange  = function()
    { 
    if(xhr.readyState == 4)
        {
            if(xhr.status  == 200) {
                var doc = xhr.responseXML;   // Assign the XML file to a var
                var courts = doc.getElementsByTagName('court');
                var index = -1;
                var LAT;
                var LNG;

                //BEGIN LOAD SEQUENCE LOGIC

                //
                // 1) get specific court information if the city_id variable is not "-1"
                //

                if (court_id!=-1){ //if the court_id variable was specified in the URL, get the city to which this single court belongs
                    for (var i = 0; i <= courts.length-1; i++) {    
                        if(courts[i].getAttribute("court_id")==court_id){//for this single court...
                            city_id = courts[i].getAttribute("city_id"); //find its city
                            LAT = courts[i].getAttribute("lat"); //record this court's location
                            LNG = courts[i].getAttribute("lng");                            
                            break; //break for loop as court has been found
                         } //end if
                     }//end for
                }//end if

                //
                // 2) load the city select and use city_id as the selected city
                //

                if (CITYSELECT==0){ 
                    var opts = [];
                    var vals = [];
                    var tempval;
                    var tempopt;
                    for (var i=0;i<=courts.length-1;i++){
                        tempval = courts[i].getAttribute("city_id");
                        tempopt = courts[i].getAttribute("city");
                        if (!valueExists(vals,tempval)){
                            vals[vals.length] = tempval;
                            opts[opts.length] = tempopt;
                        }
                    }
                    sortOptions(opts,vals);
                    writeSelect("city_select",opts,vals,city_id);
                    CITYSELECT = 1; //flag this so the select is not written again
                }

                //
                // 3) get all offices for this city_id if office_id is "0"
                //

                if (office_id==0){
                    //re-init global array
                    //resetGlobalArray();
                    var temparray = [];
                    temparray[0] = 0;
                    for (var i=0;i<=courts.length-1;i++){
                        if(courts[i].getAttribute("city_id")==city_id){// for this court...
                            recordOffices(temparray,courts[i].getAttribute("civil_scj"),courts[i].getAttribute("crim_y_ocj"),courts[i].getAttribute("crim_scj"),courts[i].getAttribute("crim_ocj"),courts[i].getAttribute("div_scj"),courts[i].getAttribute("enf_scj"),courts[i].getAttribute("fam_scj"),courts[i].getAttribute("fam_ocj"),courts[i].getAttribute("scc_scj"),courts[i].getAttribute("coa"));
                        }//end if 
                    }//end for

                    var tempvals = getUniqueValues(temparray);
                    sortArray(tempvals);
                    var tempopts = getOfficeOptions(LANGUAGE,tempvals);

                    clearSelectOptions("office_select");
                    writeSelect("office_select",tempopts,tempvals,tempvals[0]);

                } //end if office_id==0

                //
                // 4) get all courts for this city_id and office_id
                //

                for (var i = 0; i <= courts.length-1; i++) {
                    if(courts[i].getAttribute("city_id")==city_id){// for this city...
                        if(checkOffice(office_id,courts[i].getAttribute("civil_scj"),courts[i].getAttribute("crim_y_ocj"),courts[i].getAttribute("crim_scj"),courts[i].getAttribute("crim_ocj"),courts[i].getAttribute("div_scj"),courts[i].getAttribute("enf_scj"),courts[i].getAttribute("fam_scj"),courts[i].getAttribute("fam_ocj"),courts[i].getAttribute("scc_scj"),courts[i].getAttribute("coa"))){
                            var point = new google.maps.LatLng(parseFloat(courts[i].getAttribute("lat")), parseFloat(courts[i].getAttribute("lng")));
                            var tempaddress;
                            var tempcourtname;
                            var tempnotes;
                            if (LANGUAGE=="fr"){
                                tempaddress = courts[i].getAttribute("address_fr");
                                tempcourtname = courts[i].getAttribute("name_fr");
                                tempnotes = courts[i].getAttribute("notes_fr");
                            } else {
                                tempaddress = courts[i].getAttribute("address");
                                tempcourtname = courts[i].getAttribute("name");
                                tempnotes = courts[i].getAttribute("notes_en");
                            }

                            var htmlinfo = getInfoString();
                            var marker;

                            if (courts[i].getAttribute("court_id")==court_id){
                                index = Global_i;
                            }
                            //create an info marker for this court
                            //this function also writes these objects for global use
                            createInfoMarker(point,htmlinfo,iconONT,tempaddress,Global_i);
                        }//end if
                    } //end if
                }//end for

                // 
                // 4b) put the markers on the map

                var bounds = new google.maps.LatLngBounds();
                var numcourts = Global_gmarkers.length;
                for (var i = 0; i <= numcourts-1; i++){
                    Global_gmarkers[i].setMap(map);
                    bounds.extend(Global_points[i]);
                }

                //
                // 5) write elements to list box above the map canvas
                //    and activate item 0

                document.getElementById("listbox").innerHTML = Global_side_bar_html;
                topListClick(0);

            } else { 
                alert("Error code " + xhr.status);
            } //end if ==200
        } //end if ==4
    } //end function()

   xhr.open("GET", XMLFILE, true);
   xhr.send(null);

}// end load()
函数loadFromCitySelect(){
//获取选定城市
var city=getSelectedValue(“城市选择”);
加载(语言,城市,0,-1);
}
函数loadFromOfficeSelect(){
//获取选定城市
var city=getSelectedValue(“城市选择”);
var office=getSelectedValue(“office_select”);
负载(语言、城市、办公室,-1);
//语言最初是在页面首次加载时设置的
}
var Global_side_bar_html;
var全球投资者;
var Global_htmls;
var Global_i;
var全局_点;
var Global_lasti;
var courtIcon=”http://maps.google.com/mapfiles/kml/pal2/icon10.png";
var iconnt=courtIcon;
iconnt.image=courtIcon;
iconnt.iconSize=新的google.maps.Size(40,40);
iconnt.iconAnchor=新的google.maps.Point(15,15);
iconnt.infoWindowAnchor=新的google.maps.Point(17,2);
//激活信息窗口并将其存储
var infoWindow=new google.maps.infoWindow({
size:new google.maps.size(250200)//不确定这是否有用?
});
/*功能*/
/*******************/
函数createInfoMarker(点、信息、图标、名称、数值){
var marker=new google.maps.marker({
位置:点,,
图标:courtIcon,
地图:地图
});
//全球标记器推送(标记器);
google.maps.event.addListener(标记'click',函数(){
setContent(Global_htmls[num]);
信息窗口。打开(地图、标记);
//map.setCenter(marker.getPosition());
});
google.maps.event.addListener(标记'click',函数(){
document.getElementById(“printInfoBubble”).innerHTML=info;
});
全局标记器[全局标记器]=标记器;
全局htmls[Global_i]=信息;
全局_点[全局_i]=点;
全局_side_bar_html+='
'; 全局_i++; 返回标记; }//结束createInfoMarker 函数topListClick(i){ google.maps.event.trigger(Global_gmarkers[i],“click”); } 函数init(){ 变量映射选项={ 缩放:12, 中心:新google.maps.LatLng(43.717272,-79.393044), 滚轮:错误, scaleControl:对, overviewMapControl:true, overviewMapControlOptions:{opened:true}, mapTypeId:google.maps.mapTypeId.ROADMAP }; window.map=new google.maps.map(document.getElementById(“map”),mapOptions); //收集url字符串参数 LANGUAGE=getQueryVariable(“lang”);/?lang= 城市=getQueryVariable(“城市”);/?城市= COURT=getQueryVariable(“COURT”); PCODE=getQueryVariable(“PCODE”); //如果未传递url字符串参数,请使用以下作为默认值 如果(城市==“”){ CITY=122;//多伦多为默认值 } 如果(语言==“”){ LANGUAGE=“en”//默认情况下为en } 如果(法庭==“”){ COURT=-1;//没有通过任何法庭 } 如果(PCODE!=“”){ document.getElementById(“邮政编码”)。value=PCODE; } //加载语言变量 文本(语言); 负载(语言、城市、0、法院); } 功能负载(语言、城市id、办公室id、法庭id){ 全局_side_bar_html=“”; 全球市场营销员=[]; 全局htmls=[]; 全局_i=0; 全局_点=[]; 全局_lasti=-1; var-xhr; 请尝试{xhr=newActiveXObject('Msxml2.XMLHTTP');} 捕获(e) { 请尝试{xhr=newActiveXObject('Microsoft.XMLHTTP');} 渔获物(e2) {try{xhr=newXMLHttpRequest();} catch(e3){xhr=false;} } } xhr.onreadystatechange=函数() { if(xhr.readyState==4) { 如果(xhr.status==200){ var doc=xhr.responseXML;//将XML文件分配给变量 var courts=doc.getElementsByTagName(“court”); var指数=-1; var LAT; 乏液化天然气; //开始加载顺序逻辑 // //1)如果city_id变量不是“-1”,则获取具体的法庭信息 // 如果(court_id!=-1){//如果在URL中指定了court_id变量,则获取此法院所属的城市 对于(var i=0;i尝试以下更改:

  • 在函数createInfoMarker中,取消对此行的注释Global\u gmarkers.push(marker);
  • 在“加载”功能中,通过以下方式清除全局标记:

    
    
    
    对于(变量i=0;i

  • 我建议您使用不同的方法。 当你使用谷歌地图时,你有一项复杂的工作要做,就像你的情况一样,最好编写你自己的对象来管理所有的繁重工作

    因此,我建议您使用一个对象MyMarker,它将在标记中包含您所需的所有内容(信息窗口的html、图标、点…)。 然后有一个MyMarkerCollection对象,它将管理标记的集合。 如果您认为所有全局*(全局_i,全局_点…)变量都可以放入MyMarker对象或MyMarkerCollection对象,那么就可以使用它们(当使用比需要多得多的全局变量进行编码时,很容易做不需要的事情)

    你将不得不适应你的代码一点,但你会看到这是一个工作,w
    <!DOCTYPE html>
    
    <html>
    <head>    
        <title>Handling markers collection demo</title>
    
       <style type="text/css">
            html
            {
                height: 100%;
            }
            body
            {
                height: 100%;
                margin: 0;
                padding: 0;
            }
            #map-container
            {
                height: 100%;
                width: 100%;
                min-width:500px;
                min-height:300px;
            }
        </style>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>    
    
    </head>
    
    
    <body>
        <button onclick="Load1()">Load Point 1</button>
        <button onclick="Load2()">Load Point 2</button>
        <button onclick="Remove()">Remove</button>
        <div id="map-container"></div>
    
    
        <script type="text/javascript"  language="javascript">
    
            var _map;
            $(document).ready(function () {
                var mapOptions = {
                    zoom: 4,
                    center: new google.maps.LatLng(-34.397, 150.644),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                }
                _map = new google.maps.Map($("#map-container")[0], mapOptions);
            });
    
            // for the demo sake
            var points1 = [{lat:1.2345, lng: 3.45465}, {lat:-1.45467, lng: 3.54645}];
            var points2 = [{lat:2.2345, lng: -4.45465}, {lat:-2.45467, lng:-4.54645}];
    
            //very little global variables (only what you really need to be global)
            var MarkersCollection;
    
            // the custom marker object with all what you need to show along with your marker
            // and some methods in the prototype that help to manage the object
            function MyMarker(point, html) {
                this.point = point; // your point
                this.marker = new google.maps.Marker({position: this.point}); 
                this.html = html;
            }
            MyMarker.prototype.addMarkerToMap = function (map) {
                this.marker.setMap(map);
            };
            MyMarker.prototype.removeMarkerFomMap = function () {            
                this.marker.setMap(null);
            };
    
            // the collection of custom markers with the methos that help to manage the collection
            function MyMarkerCollection() {
                this.collection = [];
            }
            MyMarkerCollection.prototype.add = function (marker) {
                this.collection.push(marker);
            };
            MyMarkerCollection.prototype.removeAllMarkers = function () {
                for (var i = 0; i < this.collection.length; i++) {                
                    this.collection[i].removeMarkerFomMap();
                }
            };
            MyMarkerCollection.prototype.count= function () {                             
                return this.collection.length;               
            };
    
    
            // your load function
            function Load(points) {
    
                if (!MarkersCollection) {
                    MarkersCollection = new MyMarkerCollection();
                }
                else {
                    MarkersCollection.removeAllMarkers();
                }
                for (var i = 0; i < points.length; i++) {
                    var point = new google.maps.LatLng(points[i].lat, points[i].lng);
                    // create markers
                    var marker = new MyMarker(point, "your html");
                    marker.addMarkerToMap(_map);
                    MarkersCollection.add(marker);
    
                    _map.setCenter(point);
                }
            }
    
            // for the demo sake
            function Load1() {
                Load(points1);
            }
            function Load2() {
                Load(points2);
            }
            function Remove(){
                if(MarkersCollection)MarkersCollection.removeAllMarkers();
            }
    
        </script>
    </body>
    </html>