使用自定义链接点击

时间:2017-02-07 03:08:11

标签: javascript jquery google-maps leaflet markerclusterer

我试图在传单地图中触发标记弹出窗口,但没有运气。我正在使用群集地图,它工作正常,并在用户点击标记时打开弹出窗口。我需要扩展这个,例如通过url传递参数并根据页面加载时的url参数值打开特定标记。我使用以下代码进行地图聚类。

        var latlng = L.latLng(-30.81881, 116.16596);
    var map = L.map('lmap', { center: latlng, zoom: 6 });
    var lcontrol = new L.control.layers();
    var eb = new L.control.layers();


    //clear map first
    clearMap();
    //resize the map
    map.invalidateSize(true);
    //load the map once all layers cleared
    loadMap();
    //reset the map size on dom ready
    map.invalidateSize(true);
function loadMap() {

        var markers_array = [];

        var roadMutant = L.gridLayer.googleMutant({
            type: 'roadmap' // valid values are 'roadmap', 'satellite', 'terrain' and 'hybrid'
        }).addTo(map);


        //add the control on the map

       lcontrol= L.control.layers({
            Roadmap: roadMutant

        }, {}, {
            collapsed: false
        }).addTo(map);

    var markers = L.markerClusterGroup({chunkedLoading: true, spiderfyOnMaxZoom: true, maxClusterRadius: 80, showCoverageOnHover: true });

    //clear markers and remove all layers
    markers.clearLayers();


    $.ajax({
        type: "GET",
        url: appUrl + "/Home/map", 
        data: {'atype': st},
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        success: function (data) {

            $.each(data, function (i, item) {
                var img = (item.IconUrl).replace("~", "");
                var Icon = L.icon({ iconUrl: img, iconSize: [42, 42] });

                var marker = L.marker(L.latLng(item.Latitude, item.Longitude), { icon: Icon }, { title: item.Name });
                var content = "<div class='infoDiv'><h3><img src='" + appUrl + img + "' width='24' />" + item.Name + "</h3><p>" + item.Title + "</p><a href='#' data-value='" + item.AlertId + "' class='btn btn-success btn-sm alertInfo' data-toggle='modal' data-target='#alertDetails'>Details</a></div>";
                marker.bindPopup(content);
                markers.addLayer(marker);
                //add the marker to array
                markers_array.push(marker);

            });

        }

    })
   .done(function () {
       $(".loadingOverlay").hide();
       map.invalidateSize(true);
   });

    //add the markers to the map
   map.addLayer(markers);

}

我试图实现以下自定义点击事件,但没有运气。

function markerFunction(id) {
       alert(markers_array.length);

       for (var i = 0; i < markers.length; ++i) {
           var mid = markers_array[i]["_leaflet_id"];

           if (mid == id) {
                alert("opening " + id);
               map.markers(id).openPopup();

               }
           }
          }
    //trigger on link click
   $("a").click(function () {
       var id = $(this).attr("id");
       alert(id);
       markerFunction(id);

   });

非常感谢帮助。提前谢谢。

2 个答案:

答案 0 :(得分:1)

loadMap()异步获取其数据。任何与该数据一起使用的东西(或从该数据派生的任何东西)必须以考虑异步的方式进行,通常在链式.then()中。

目前,标记是异步创建的,但单击处理程序是独立定义和附加的。通过markers_array返回的承诺提供markers(和loadMap()?)将允许在附件点完全填充必要的标记数据,并将其置于点击处理程序的范围内。

我会写这样的东西:

var latlng = L.latLng(-30.81881, 116.16596);
var map = L.map('lmap', { center: latlng, zoom: 6 });
var lcontrol = new L.control.layers(); // necessary?
var eb = new L.control.layers(); // necessary?

clearMap(); // why, it's only just been created?
map.invalidateSize(true);
loadMap(map).then(function(obj) {
    $(".loadingOverlay").hide();
    map.invalidateSize(true); // again?

    $("a").click(function(e) { // jQuery selector probably needs to be more specific
        e.preventDefault();
        var id = $(this).attr('id');
        for(var i=0; i<obj.markers_array.length; ++i) {
            if(obj.markers_array[i]._leaflet_id == id) {
                map.markers(id).openPopup(); // if `map.markers` is correct, maybe you don't need obj.markers?
                break; // break out of `for` loop on success.
            }
        }
    });
    return obj;
});

function loadMap(map) {
    var roadMutant = L.gridLayer.googleMutant({ type: 'roadmap' }).addTo(map);
    var lcontrol = L.control.layers({Roadmap: roadMutant}, {}, {collapsed: false}).addTo(map);

    return $.ajax({
        type: 'GET',
        url: appUrl + '/Home/map', 
        data: {'atype': st},
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded'
    }).then(function (data) {
        var markers = L.markerClusterGroup({chunkedLoading: true, spiderfyOnMaxZoom: true, maxClusterRadius: 80, showCoverageOnHover: true });
        markers.clearLayers();
        var markers_array = $.map(data, function(item) {
            var img = (item.IconUrl).replace("~", "");
            var Icon = L.icon({ iconUrl: img, iconSize: [42, 42] });
            var marker = L.marker(L.latLng(item.Latitude, item.Longitude), { icon: Icon }, { title: item.Name });
            var content = "<div class='infoDiv'><h3><img src='" + appUrl + img + "' width='24' />" + item.Name + "</h3><p>" + item.Title + "</p><a href='#' data-value='" + item.AlertId + "' class='btn btn-success btn-sm alertInfo' data-toggle='modal' data-target='#alertDetails'>Details</a></div>";
            marker.bindPopup(content);
            markers.addLayer(marker);
            return marker;
        });
        map.addLayer(markers); //add the markers to the map
        // If both 'markers_array' and 'markers' are needed later, then bundle them into an object.
        // If not, then simply return one or other of those variables.
        return {
            'markers_array': markers_array,
            'markers': markers
        };
    });
}

细节需要检查,但整体模式应该是正确的。

答案 1 :(得分:0)

在花了太多时间之后,我想出了一个不同的方法。通过URL传递参数作为哈希(#)值。使用jQuery选择器获取值并获取该记录的数据,然后在地图上打开弹出窗口。这是我的第二个代码块 -

&#13;
&#13;
$(function () {
           var hash = window.location.hash.substr(1);// "90aab585-1641-43e9-9979-1b53d6118faa";
           
           if (!hash) return false;
          
           //show loading
           $(".loadingOverlay").show();


           $.ajax({
               type: "GET",
               url: appUrl + "/Home/GetAlert/"+hash, 
               dataType: 'json',
               contentType: 'application/x-www-form-urlencoded',
               success: function (data) {
                   if (!data.status)
                   {
                       $('#msg').html(data.message).attr("class","alert alert-warning");
                       $(".loadingOverlay").hide();
                       return false;
                   }
                   $.each(data.message, function (i, item) {
                      
                       var popupLoc = new L.LatLng(item.Latitude, item.Longitude);
                       var popupContent = "<div class='infoDiv'><h3><img src='" + appUrl + img + "' width='24' />" + item.Name + "</h3><p>" + item.Title + "</p><a href='#' data-value='" + item.AlertId + "' class='btn btn-success btn-sm alertInfo' data-toggle='modal' data-target='#alertDetails'>Details</a></div>";

                       //initialize the popup;
                     var popup = new L.Popup();
                       //set latlng
                       popup.setLatLng(popupLoc);
                       //set content
                       popup.setContent(popupContent);
                       map.setView(new L.LatLng(item.Latitude, item.Longitude), 8);
                      //display popup
                       map.addLayer(popup);
                      
                   });

               }

           })
       .done(function () {
           $(".loadingOverlay").hide();        
           map.invalidateSize(true);
       });
          
       });
&#13;
&#13;
&#13;