【问题标题】:d3: Text displayed when clicked on leaflet mapd3:点击传单地图时显示的文字
【发布时间】:2015-04-24 18:42:25
【问题描述】:

当我单击传单地图上的 geoJSON 图层时,我正在尝试让鼠标显示一个弹出窗口。现在,当我将鼠标悬停在右上角时,我只会在右上角显示文本。

代码如下。错误发生在 onMapClick 函数期间(从 Leaflet 快速启动地图镜像)

      function highlightFeature(e) {
        var layer = e.target;
        layer.setStyle({
          weight: 10,
          color: '#666',
          dashArray: '',
          fillOpacity: 0.5
        });
        if (!L.Browser.ie && !L.Browser.opera) {
          layer.bringToFront();
        }
        info.update(layer.feature.properties);
      }

      var geojson;

      function resetHighlight(e) {
        geojson.resetStyle(e.target);
        info.update();
      }

      var popup = L.popup();
      // ***ERROR BEGINS HERE***
      function onMapClick(e) {
        popup
        //   Ideally I'd want this text to pop up when clicked
        //   This code block to create this text is located towards the end.
        //     '<b>'  + 'Block ID:</b>' + feature.hexid + '<br>'  +
        //     '<b> Population: </b>' + feature.count + '<br>' +
        //     '<b>' + 'Estimated Score: </b>' + feature.score + '<br> ' +
        //     : '');
        // };
          .setContent("Text here " + feature.count)
          .openOn(map);
        }


      function onEachFeature(feature, layer) {
        layer.on({
          mouseover: highlightFeature,
          mouseout: resetHighlight,
          click: onMapClick //doesn't work 
        });
      }


      geojson = L.geoJson(data, {
        style: style,
        onEachFeature: onEachFeature
      }).addTo(map);


        var info = L.control();
        info.onAdd = function (map) {
          this._div = L.DomUtil.create('div', 'info');
          this.update();
          return this._div;
        };
        // this is the text I want displayed on the popup
        info.update = function (feature) {
          this._div.innerHTML = (feature ?
            '<b>'  + 'Block ID:</b>' + feature.hexid + '<br>'  +
            '<b> Population: </b>' + feature.count + '<br>' +
            '<b>' + 'Estimated Score: </b>' + feature.score + '<br> ' +
            : '');
        };
        info.addTo(map);


      };

   </script>

提前致谢!

【问题讨论】:

    标签: javascript d3.js leaflet


    【解决方案1】:

    我认为您的 onEachFeature 需要进行一些更改。onMapClick 收到了 e,但您正在尝试处理 feature。 我认为你应该放弃onMapClick 并改用下面的。

    function onEachFeature(feature, layer) {
        layer.bindPopup("Text here " + feature.count);
    }
    

    还有其他一些事件变化。

    geojson.on('mouseover', highlightFeature)
    geojson.on('mouseout', resetHighlight)
    

    【讨论】:

    • 使用这种方法我不断收到错误Uncaught TypeError: Cannot read property 'on' of undefined。我是 d3 的新手,所以我可能执行不正确。
    • 你能更新你的代码块吗?更好的是,把它放到一个 js fiddle 中。
    猜你喜欢
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2021-04-05
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多