我是React和D3的新手,想要用D3 v6.2和ReactJS实现一个简单的SVG地图,用来标示一些城市的位置。目前每个城市都用圆形表示,如下图所示:
我需要将这种标记改成像下面这张图片一样带有城市名称的图钉(如果可能使用div):
但是点的符号形状是由D3-path本身确定的,我找不到任何可以更改或替换为其他标记的方法。
注意:我尝试在点的path
标记中放置一个div
,但我发现它们没有被渲染出来。我唯一能够做的改变是用pointRadius()
改变标记的半径,但我不想这样做。
代码:
import React, { useEffect, useRef, useState } from 'react';
import { select, geoPath, geoMercator } from "d3";
import useResizeObserver from 'use-resize-observer';
import drawMap from './mapa.json';
import dataMap from './city.json';
const svgRef = useRef(null);
const wrapperRef = useRef(null);
const { widthRef, heightRef } = useResizeObserver({ wrapperRef });
function map(){
useEffect(() => {
const svg = select(svgRef.current);
const { width, height } = wrapperRef.current.getBoundingClientRect();
const projection = geoMercator().fitSize([width, height], selectedEstados || drawMap);
let pathGenerator = geoPath().projection(projection).pointRadius(4);
console.log("path: " + pathGenerator)
svg.selectAll(".estado")
.data(drawMap.features)
.join("path")
.attr("class", "estado")
.attr("d", features => pathGenerator(features));
svg.selectAll(".city")
.data(dataMap.features)
.join("path")
.attr("class", "city")
.attr("d", features => pathGenerator(features))
}, [drawMap, wrapperRef, widthRef, heightRef])
return(
<div className='map' ref={wrapperRef}>
<svg ref={svgRef}></svg>
</div>
)
}
city.json
{
"type": "FeatureCollection",
"name": "city",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [
{
"type": "Feature",
"properties": {
"municipio": "sapé"
},
"geometry": {
"type": "Point",
"coordinates": [
-41.821476100786512,
-8.282815195947387
]
}
},
{
"type": "Feature",
"properties": {
"municipio": "muito distante"
},
"geometry": {
"type": "Point",
"coordinates": [
-41.065329661162544,
-7.183034162673664
]
}
}
]
}
mapa.json