简体   繁体   English

Google Maps API v.3在单击标记时清除并添加标记

[英]Google Maps API v.3 Clearing and adding markers on marker click

I am pulling markers from a MySQL database table of locations, which uses a nested set model for hierarchical categorization. 我从位置的MySQL数据库表中提取标记,该表使用嵌套集模型进行分层分类。 That part is working well. 该部分运行良好。 I can place all markers on the map, using MarkerManager to show/hide at different zoom levels (using the 'depth' field from my table). 我可以使用MarkerManager在不同的缩放级别(使用表格中的“深度”字段)显示/隐藏所有标记,将它们放置在地图上。 That works nicely. 那很好。 My issue is that if a marker for a country is clicked on, I would like all markers outside that country to be removed. 我的问题是,如果单击某个国家的标记,则希望删除该国家以外的所有标记。 Getting a single country's markers is trivial, I just feed a parent id to the xhr function. 获取单个国家/地区的标记是微不足道的,我只需将父ID馈入xhr函数即可。 But clearing the markers... this is stumping me. 但是清除标记...这让我很沮丧。 I've been working at it for days, and just can't seem to make headway. 我已经为此工作了好几天,但似乎并没有取得进展。

Here is the business-end of the JS 这是JS的业务端

        var map         = new google.maps.Map(document.getElementById('gMap'), mapOptions);
    // init the markerManager
    var mgr         = new MarkerManager(map);
    //Associate the styled map with the MapTypeId and set it to display.
    map.mapTypes.set('Dark', darkMap);
    map.mapTypes.set('Light', lightMap);
    map.setMapTypeId('Dark'); 

    // lat lng bounds for center/zoom marker
    var bounds      = new google.maps.LatLngBounds();

    // infowindow (infobox)
    // init here, and re-use
    var ib          = new InfoBox();
    var oldDraw     = ib.draw;
    ib.draw         = function() {
        oldDraw.apply(this);
        jQuery(ib.div_).hide();
        jQuery(ib.div_).fadeIn('slow');
    }

    // init marker list
    // for removing 'old' markers and loading new ones
    var markersArray= [];

    // load markers from database

    function loadMarkers(params) {
        var params = params || {};
        var pid = params.pid || 5;
        deleteOverlays(pid,function(){
            // alert("deleteOverlays(" + pid + ");")
            $.getJSON('/map/xhr_get_descendants', {
                pid : pid
            }, function(data) {
                var bounds = new google.maps.LatLngBounds();
                $.each(data, function(key, val) {
                    if (val.lat_long && val.lat_long != '') {
                        var name = val.name;
                        var id = val.id;
                        var depth = val.depth;
                        var children = val.children;
                        var pos = val.lat_long.split(',');
                        var lat = parseFloat(pos[0]);
                        var long = parseFloat(pos[1]);
                        var myLatLng = new google.maps.LatLng(lat, long);
                        var html = "<b>NAME=>" + name + "\nID=>" + id + "\nDEPTH=>" + depth+"</b>";
                        var marker = new google.maps.Marker({
                            position : myLatLng
                        });
                        mgr.addMarker(marker, depth);
                        markersArray.push(marker);
                        var boxText = document.createElement("div");
                        google.maps.event.addListener(marker, 'mouseover', function() {
                            /*
                             getStats(id);
                             //  */
                            boxText.innerHTML = html;
                            var infoBoxOptions = {
                                content : boxText,
                                disableAutoPan : true,
                                maxWidth : 0,
                                pixelOffset : new google.maps.Size(-140, 0),
                                zIndex : null,
                                boxClass : "infoBox",
                                closeBoxMargin : "2px 2px 2px 2px",
                                closeBoxURL : "http://www.google.com/intl/en_us/mapfiles/close.gif",
                                infoBoxClearance : new google.maps.Size(10, 10),
                                isHidden : false,
                                pane : "floatPane",
                                enableEventPropagation : false,
                            };
                            ib.setOptions(infoBoxOptions);
                            ib.open(map, marker);
                        })
                        google.maps.event.addListener(marker, 'mouseout', function() {
                            ib.close();
                        })

                        google.maps.event.addListener(marker, 'click', function() {
                            map.panTo(this.getPosition());
                            // getLinks(id);
                            if (children > 0) {
                                loadMarkers({
                                    pid : id
                                });
                            }
                        })
                        bounds.extend(myLatLng);
                    }
                });
                map.fitBounds(bounds);
            });
        });
    }


    // clear markers
    function deleteOverlays(pid,callback){
        if((markersArray)&&(markersArray.length > 1)) {
            for (var x in markersArray) {
                markersArray[x].setMap(null);
                markersArray[x]=null;
            }
            markersArray=[];
        };
        callback(pid);
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
        google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
        });
    }

    loadMarkers({
        pid:5
    });

So quickly, you can see that I send a parent id to the loadMarkers() among other things if necessary, and do some stuff, and then I call the deleteMarkers() function, the callback of which creates the markers, adds them to the manager and to the main markersArray[] 很快,您可以看到我在必要时向其他对象发送了一个父ID到loadMarkers(),并做了一些工作,然后调用deleteMarkers()函数,该函数的回调创建了标记,并将它们添加到了经理和主要的markersArray []

for brevity I'm not going to add the full Ajax call to xhr_get_descendants/ because without the Model it would be a bit meaningless. 为了简洁起见,我不会将完整的Ajax调用添加到xhr_get_descendants /中,因为如果没有Model,那将毫无意义。 Anyway, the function returns id, name, depth of each "child" of the parent id provided, as well as how many children each one of those children might have. 无论如何,该函数会返回ID,名称,所提供的父ID的每个“子”的深度,以及每个子可能有多少个子。

I mean... this should work!!! 我的意思是...这应该工作!!! LOL I've been looking at it wayyyy too long. 大声笑我一直在看它wayyyy太久了。 I'd seriously appreciate any suggestions, or hints, or even a "why the hell are you doing it this way?" 我将非常感谢您提出的任何建议或提示,甚至是“您为什么要这么做呢?”

The markers displayed by the MarkerMangager are not the markers you create (and supply as argument to mgr.addMarker() ), the MarkerManager creates new Instances and these Instances will not be deleted when you delete the Markers stored in markersArray (what doesn't have any visual effect, because the markers stored in markersArray are not visible) MarkerMangager显示的标记不是您创建的标记(并作为mgr.addMarker()参数提供),MarkerManager会创建新的实例,并且当您删除存储在markersArray的Markers时,这些实例不会被删除(不会具有任何视觉效果,因为存储在markersArray中的标记不可见)

You may call mgr.clearMarkers() in deleteOverlays() to delete also the Instances created by the MarkerManager, but the complete approach with the markersArray is unnecessary. 您可以在deleteOverlays()调用mgr.clearMarkers()来同时删除MarkerManager创建的实例,但是不需要使用markersArray的完整方法。 You don't need this array at all, simply call mgr.clearMarkers() to remove the visible Markers. 您根本不需要此数组,只需调用mgr.clearMarkers()即可删除可见的Markers。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM