【问题标题】:Scale/zoom D3 layer on Leaflet map to layer bounds将 Leaflet 地图上的 D3 图层缩放/缩放到图层边界
【发布时间】:2016-02-27 08:02:10
【问题描述】:

我正在使用 Leaflet 创建一个在顶部添加了 D3 图层的地图。我想自动缩放到覆盖层,类似于在纯 D3 (see example) 中自动将地理对象放入其容器中的方式。

为了让 Leaflet 和 D3 玩得很好,我必须使用每个 this example 的自定义地理转换:

function projectPoint(x, y) {
  var point = map.latLngToLayerPoint(new L.LatLng(y, x));
  this.stream.point(point.x, point.y);
}

var transform = d3.geo.transform({point: projectPoint}),
    path = d3.geo.path().projection(transform);

这使得将 D3 投影到 Leaflet 地图上毫不费力,但我对如何确定图层地图的纬度/经度一无所知。我需要这些坐标来设置中心,然后我还需要设置缩放级别。

如何在 Leaflet 中自动设置 setViewsetZoom 以适应 D3 覆盖层?

这是我的实现:

var map = new L.Map("map", {
    // Initialize map with arbitrary center/zoom
    center: [37.8, -96.9], 
    zoom: 4
})

var layer = map
    .addLayer(new L.TileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"));

var figure = d3.select('figure');
var width = figure.node().clientWidth;
var height = figure.node().clientHeight;

var svg = d3.select(map.getPanes().overlayPane)
    .append("svg")
    .style('width', width)
    .style('height', height);

var g = svg.append("g").attr("class", "leaflet-zoom-hide");

function projectPoint(x, y) {
    var point = map.latLngToLayerPoint(new L.LatLng(y, x));
    this.stream.point(point.x, point.y);
}

var transform = d3.geo.transform({ point: projectPoint });
var path = d3.geo.path().projection(transform);

d3.json('conway-ar.json', function(error, collection) {
    if (error) console.warn(error);

    var city = g.append('path')
        .datum(collection.city.geometry)
        .attr('fill', 'none')
        .attr('stroke', 'blue')
        .attr('d', path);

    // Update center/zoom based on location of "city"
    // map.setView([someLat, someLng]);
    // map.setZoom(someZoomLevel);

    map.on('viewreset', update);
    update();

    function update() {
        city.attr('d', path);
    }

});

【问题讨论】:

    标签: javascript d3.js leaflet


    【解决方案1】:

    我能够使用 Leaflet.D3SvgOverlay 实现一个解决方案,这是一个将 D3 与 Leaflet 一起使用的库,可以自动进行地理转换。

    首先我用proj.pathFromGeojson.bounds(d) 记录了渲染路径的边界。这个库有一个方便的方法,可以将图层点转换为纬度/经度,proj.layerPointToLatLng。然后我可以使用 D3 的map.fitBounds 根据记录的边界同时调整中心/缩放。见以下代码:

    var bounds = [];
    var city = sel.append('path')
      .datum(cityGeo)
      .attr('d', function(d) {
        bounds = proj.pathFromGeojson.bounds(d);
        return proj.pathFromGeojson(d); 
      });
    
    var b = [proj.layerPointToLatLng(bounds[0]),
             proj.layerPointToLatLng(bounds[1])];
    map.fitBounds(b);
    

    这个的完整实现可以在我的bl.ock看到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      相关资源
      最近更新 更多