首页 > 解决方案 > Vue 应用程序中的 d3 - 如何在地图上应用缩放

问题描述

我想将此示例实现为 Vue.js 应用程序:

https://blockbuilder.org/adkdev/fe15a54ad3748c72e059475e3f43d462

我的方法是这样的:

<template>
    <svg>
       <path
        v-for="(item, index) in features"
        :key="index"
        :stroke-width="countyBorderWidth"
        :class="{ active: isActive(index) }"
        :d="geoPath(item)"
        v-on:click="clickedCountry(index, item.id)"
      >
    </svg>
</template>
<script>
 projection() {
      const p = d3.geoNaturalEarth1();
      p.fitSize([this.width, this.height], this.features);
      return p;
    },
 geoPath() {
   return d3.geoPath().projection(this.projection);
 },
 zoom(item) {
    // TODO
 }
</script>

然后让zoom()方法进行缩放。

我的问题是缩放部分,因为在示例中它被调用g

// Zoom
 g.transition()
.duration(750)
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')scale(' + k + ')translate(' + -x + ',' + -y + ')');

您如何将这个示例转换为 Vue 应用程序,具体来说,您将如何实现地图的缩放?

谢谢你的帮助!

标签: vue.jsd3.jsvuejs2

解决方案


你很好地识别了问题。缩放是在( g) 上进行的。

既然你没有,<g>你可以像这样添加它:

<template>
  <svg>
    <g>
      <path
        v-for="(item, index) in features"
        :key="index"
        :stroke-width="countyBorderWidth"
        :class="{ active: isActive(index) }"
        :d="geoPath(item)"
        v-on:click="clickedCountry(index, item.id)"
      >
    </g>
  </svg>
</template>

然后在方法中选择它zoom

zoom(item) {
    d3.select('g').transition()
      .duration(750)
      .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')scale(' + k + ')translate(' + -x + ',' + -y + ')');

如果您想<g>省略并继续您拥有的内容,请<svg>直接选择:

zoom(item) {
    d3.select('svg').transition()
      .duration(750)
      .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')scale(' + k + ')translate(' + -x + ',' + -y + ')');

}

或者,您可以在组件的一部分中做所有事情,只<script>留下部分:<svg><template>

<template>
  <svg></svg>
</template>

然后您指定样式和属性,并像click使用 D3.js一样管理事件。那将是链接示例中的代码。您需要重新组织它并将其分组为几个方法。


推荐阅读