当用户缩放地图时,我试图减小标签的大小。我认为如果地图缩放,它将自动减少。但这没有发生。我在项目中使用d3地图。
这里我使用的是svg,因此我们必须根据地图的大小或缩放比例动态地提供字体。
这是我的代码:
d3.select(".map-container").select('svg').remove()
d3.select(".d3-tip").remove()
let width = $('.map-container').width()
let height = $('.map-container').height()
const zoom = d3.zoom()
.scaleExtent([1, 40])
.translateExtent([[0,0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
//this is my zoom function
function zoomed(){
g.attr("transform", d3.event.transform);
}
let svg = d3.select(".map-container").append("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", "0 0 " + width.toFixed(0) + " " + height.toFixed(0))
.call(zoom);
// this is my function to display text
function drawSubUnitLabels(level, data, obj_key, mp_data) {
d3.select('.map-container svg g').selectAll(".map-label").remove()
d3.select('.map-container svg g').selectAll(".map-name").remove()
d3.select('.map-container svg g').selectAll(".subunit-label")
.data(topojson.feature(data, data.objects[obj_key]).features)
.attr("y", "-5")
.attr("rx", "5")
.attr("ry", "5")
.attr("width", function() {
if (level === 'india')
return "40"
else if (level == 'state')
return '80'
})
.attr("height", "10")
.attr("fill", "#fff")
.attr('opacity', function() {
if (options['m_names'][0] === 'true' || options['m_score'][0] === 'true')
return 1
return 0
})
.attr('class', function(d) {
if ((level === 'india') && (options['state_id'][0] === 'IN' || options['state_id'][0] === state_code_mapping[d.properties.ST_NM]))
return "map-label"
else if (level === 'state' && (options['district_id'][0] === '' || options['district_id'][0] === d.properties.D_CODE))
return "map-label"
else
return "map-label d-none"
})
d3.select('.map-container svg g').selectAll(".subunit-label")
.data(topojson.feature(data, data.objects[obj_key]).features)
.enter().append("text")
.attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.style("font-size", ".625rem")
.style("text-transform", "uppercase")
.attr('class', 'map-name')
.attr('data-state-id', function(d) {
return d.properties.ST_NM
})
.text(function(d) {
let value = mp_data[d.properties.D_CODE] ? mp_data[d.properties.D_CODE] : 'NA'
if (options['district_id'][0] === '' || options['district_id'][0] === d.properties.D_CODE) {
if (options['m_names'][0] === 'true' && options['m_score'][0] === 'true')
return d.properties.D_NAME + ":" + value
else if (options['m_names'][0] === 'true')
return d.properties.D_NAME
else if (options['m_score'][0] === 'true')
return value
else
return
}
})
}
有人可以帮我吗?