使用OpenLayers 3从SVG图像创建一个图层

4

我正在尝试将大型SVG文件作为Open Layers 3地图上的一个图层使用。 我只想显示SVG,而不带任何底图。 尝试获取答案时,一些信息提到了使用图标标记来实现,但我无法使其正常工作。

有人知道如何简单地显示SVG文件作为图层吗?


在地图的“postcompose”事件中,您可以获取画布上下文并在地图顶部绘制。也许这就是您想要的?在地图上添加“postcompose”事件侦听器...您应该能够找到一些使用它的示例。 - ryansstack
您可能需要将其转换为一组向量,否则 ol 图层中的对象需要被地理定位,否则渲染器不知道在绘制 SVG 时与其他所有内容相关的位置。 - softwarenewbie7331
我没有问题将其转换为向量,但由于它不是地理数据,所以我无法进行地理定位。 - amitdar
为什么您想要显示没有地图底图的SVG,它受OpenMaps的限制是什么?您能详细说明您正在尝试做什么或分享一些代码吗? - Taran J
2个回答

1
默认情况下,图层中的对象需要进行地理定位,以便渲染器知道在哪里绘制它们。我发现的一个技巧是使用D3将svg特征映射为向量,并使用自定义投影函数为渲染器处理。它还处理监听移动/平移。参见:http://bl.ocks.org/pbogden/6283017 以下是该解决方案的一些代码:
d3.json("us-states.json", function(err, collection) {
    var bounds = d3.geo.bounds(collection),
        path = d3.geo.path().projection(project), // create a d3.geo.path that converts GeoJSON to SVG
        vector = new OpenLayers.Layer.Vector( "states" ); // create a vector layer

    // Use D3 to add the states after the vector layer has been added to the map
    vector.afterAdd = function() {
        var div = d3.select("#"+vector.div.id);
        div.selectAll("svg").remove();  // Prepare OpenLayers vector div to be the container for D3

        var svg = div.append("svg"),
            g = svg.append("g");

        var states = g.selectAll("path")
                .data(collection.features)
              .enter().append("path");

        reset();

        // Reposition the SVG to cover the features
        function reset() {
            var bottomLeft = project(bounds[0]),
                topRight = project(bounds[1]);

            svg .attr("width", topRight[0] - bottomLeft[0])
                .attr("height",bottomLeft[1] - topRight[1])
                .style("margin-left", bottomLeft[0] + "px")
                .style("margin-top", topRight[1] + "px");

            g   .attr("transform", "translate(" + -bottomLeft[0] + "," + -topRight[1] + ")")

            states.attr("d", path);
        };
        map.events.register("moveend", map, reset);
    };
    // Add the vector layer to the map
    map.addLayer(vector);

   // Use OpenLayers to implement a custom D3 geographic projection.
   // Converts lon/lat to viewport coordinates (D3 uses 2-element arrays).
   function project(x) {
       var point = map.getViewPortPxFromLonLat( new OpenLayers.LonLat(x[0], x[1])
                                                    .transform("EPSG:4326", "EPSG:900913")
       );
       return [ point.x, point.y ];
   }
});

1

我刚在另一个类似的问题中回答了这个问题。请参见那个答案,其中包含可运行的示例。

要点:只需将svg文件作为ol.source.ImageStatic的url包含即可。


如果其他问题是相同的,那么应该将其中一个关闭为重复。如果不是相同的,则答案可以针对此问题的特定问题进行调整。请参阅:是否可以向多个问题添加重复答案? - Mogsdad
谢谢,我赞同将此问题标记为其他问题的重复。 - Alvin Lindstam
哇,太棒了!正是我在寻找的,谢谢伙计。 - amitdar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接