首页 > 解决方案 > D3 geojson地图鼠标事件触发“差”

问题描述

我正在使用 geojson 中的 D3 创建一个等值线。地图具有与县相关的 mouseover 和 mouseout 事件。问题:只有当鼠标在组成县的路径上缓慢而精确地移动时才会触发事件。如果我更快地将鼠标移到地图上,则根本不会触发事件。当鼠标越过县线时,只会触发一个事件。本质上,我想将事件与代表县的区域联系起来,而不是与绘制它们的线/路径联系起来。我之前为美国的县制作了相同类型的地图,并使用相同的方法和鼠标事件功能,结果是事件被顺利触发。所以我认为这与 svg/map 不是我的方法有关吗?

也尝试使用 topojson ,但没有任何区别。geojson 文件是从带有 EPSG:3301 投影的 shp 文件转换而来的。

let width = 1000;
    let height = 550;

    let svg = d3.select('#viz')
                .append('svg')
                .attr('width', width)
                .attr('height', height)

    let tooltip = d3.select('#viz')
                    .append('div')
                    .attr('id', 'tooltip')

    let projection = d3.geoIdentity()
                        .reflectY(true)


    fetch('https://raw.githubusercontent.com/keijop/counties_geojson/main/maakond_20210301.json')
        .then(response => response.json())
        .then(data => {
            
            console.log(data)
            
            projection.fitSize([width,height], data)

            svg.selectAll('path')
                .data(data.features)
                .enter()
                .append('path')
                .attr('d', d3.geoPath().projection(projection))
                .attr('data-county', d => d.properties.MNIMI)
                .attr('data-ehak', d => d.properties.MKOOD)

                .on('mouseover', (e,d) =>{
                    console.log(e.target)
                    d3.select('#tooltip')
                        .style('top', e.pageY+10+'px')
                        .style('left', e.pageX+10+'px')
                        .style('opacity', '1')
                        .html(
                            e.target.getAttribute('data-county')
                            )
                        e.target.style.fill = 'yellow'
                    })

                .on('mouseout', (e,d) => {
                    e.target.style.fill = 'none'
                    d3.select('#tooltip')
                        .style('opacity', 0)

                    })
        });

小提琴:https ://jsfiddle.net/zrnp3xq9/ 。
期望的结果:https ://codepen.io/KeijoP/pen/VwPZMmb

标签: javascriptd3.jsmouseeventgeojsonchoropleth

解决方案


推荐阅读