首页 > 解决方案 > 使用 d3-tip.js 在 d3 和 Leaflet.js 地图上显示弹出窗口,但无法在该弹出窗口中显示相关标记数据

问题描述

我正在使用 d3.js、d3-tip.js 和 leaflet.js 的组合来显示带有气泡图叠加层的地图。我使用 Flask 作为 Web 框架。

我设法让我的地图显示出来,我的气泡要覆盖,我的工具提示要显示。我坚持的部分是我希望工具提示显示相关气泡的值,即“订单”计数。我被困在如何让弹出窗口知道底层值是什么(在我的 const 标记列表中,它将是 'o' 值)。

这是我的整个地图脚本:

<script>

    // mapid is the id of the div where the map will appear
    const map = L
      .map('mapid')
      .setView([-27.833, 133.583], 5);   // center position + zoom
    
    // Add a tile to the map = a background. Comes from OpenStreetmap
    L.tileLayer(
        'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a>',
        maxZoom: 20,
        maxNativeZoom: 18
        }).addTo(map);
    
    // Add a svg layer to the map
    L.svg().addTo(map);
    
    // Create data for circles:
    const markers = [ 
        {% for o in orders  %}
            {long: {{o.long}}, lat: {{o.lat}}, o:{{o.order_count}}},
        {% endfor %}
        ];
   
    var svg = d3.select("svg");
    var tool_tip = d3.tip()
      .attr("class", "d3-tip")
      .offset([-10, 0]).html(d => {
      return (
        "<strong>Orders:</strong> <span style='color:white'>" + d.o + "</span>"
       );
     });
    svg.call(tool_tip);

    // Select the svg area and add circles:
    d3.select("#mapid")
      .select("svg")
      .selectAll("myCircles")
      .data(markers)
      .join("circle")
        .attr("cx", d => map.latLngToLayerPoint([d.lat, d.long]).x)
        .attr("cy", d => map.latLngToLayerPoint([d.lat, d.long]).y)
        .attr("pointer-events","visible")
        .attr("r", d => d.o)
        .style("fill", "red")
        .attr("stroke", "red")
        .attr("stroke-width", 3)
        .attr("fill-opacity", .4)    
        .on('mouseover', tool_tip.show)
        .on('mouseout', tool_tip.hide);

    // Function that update circle position if something change
    function update() {
      d3.selectAll("circle")
        .attr("cx", d => map.latLngToLayerPoint([d.lat, d.long]).x)
        .attr("cy", d => map.latLngToLayerPoint([d.lat, d.long]).y)
        .attr("pointer-events","visible")
      }
    
    // If the user change the map (zoom or drag), I update circle position:
    map.on("moveend", update)
      
    </script>

目前我在工具提示中得到一个“未定义”的文本。

在此处输入图像描述

标签: javascriptd3.jsleaflettooltip

解决方案


推荐阅读