Mapbox:点击地图外部,打开标记的弹出窗口

时间:2016-05-05 08:51:23

标签: javascript leaflet mapbox mapbox-gl-js

我的代码中有一些div" connected"到我的地图标记。我的div有唯一的ID,我的标记与属性(title和marker-id)具有相同的ID。点击div时有没有办法打开标记弹出窗口?这是我的代码:

$('#alldealers .dealer').each(function(){
    t = $(this).find('h2').text();
    lat = $(this).find('.lat');
    lng = $(this).find('.lng');  
    userLng = parseFloat($(lng).text());
    userLat = parseFloat($(lat).text());   
    subUniqueNum = $(this).attr('data-link');

    L.mapbox.featureLayer({
        type: 'Feature',
        geometry: {
            type: 'Point',
            coordinates: [userLng, userLat]
        },
        properties: {
            title: subUniqueNum,
            'marker-id': subUniqueNum,
            'marker-size': 'small',
            'marker-color': '#f85649',
        }
    }).bindPopup('<button class="giveMeDetails" data-attr-scroll="'+subUniqueNum+'">'+t+'</button>').addTo(map);   
});

$('.mapicon_wrapper').click(function(e){    
    tot_p = $(this).parent().parent().parent().attr('id');//parent wrapper id:same as marker's ID
    $root.animate({
        scrollTop: $('html').offset().top
    }, 500, function () {

        // This is where I need to open the markers popup with the same title as $this parent ID (tot_p)

    });        
});

1 个答案:

答案 0 :(得分:1)

这种为标记分配ID并在DOM中调用它的方法不可靠:如果标记位于当前查看的地图区域之外,则它不会出现在DOM中。一个正确的方法是

var markerLayer = L.mapbox.featureLayer().addTo(map);
var markers = [];
$('#alldealers .dealer').each(function(){
    t = $(this).find('h2').text();
    lat = $(this).find('.lat');
    lng = $(this).find('.lng');  
    userLng = parseFloat($(lng).text());
    userLat = parseFloat($(lat).text());   
    subUniqueNum = $(this).attr('data-link');

    markers.push({
        type: 'Feature',
        geometry: {
            type: 'Point',
            coordinates: [userLng, userLat]
        },
        properties: {
            title: subUniqueNum,
            id: subUniqueNum,
            t: t,
            'marker-size': 'small',
            'marker-color': '#f85649',
        }
    })
});

markerLayer.setGeoJSON(markers);

markerLayer.eachLayer(function (layer) {
  layer.bindPopup('<button class="giveMeDetails" data-attr-scroll="'+layer.feature.properties.title+'">'+layer.feature.properties.t+'</button>');   
});

$('.mapicon_wrapper').click(function(e){    
    var tot_p = $(this).parent().parent().parent().attr('id');//parent wrapper id:same as marker's ID
    $root.animate({
        scrollTop: $('html').offset().top
    }, 500, function () {

        // This is where I need to open the markers popup with the same title as $this parent ID (tot_p)
    markers.eachLayer(function (layer) {
      if (layer.feature.properties.id === tot_p) {
        layer.openPopup();
      }
    });
    });        
});