繁体   English   中英

将SVG对象而不是文件添加到LeafletJs

[英]Add SVG object instead of file to LeafletJs

我想将修改后的SVG对象添加到地图而不是原始文件。

$.ajax({
        method: 'get',
        url: 'zones.svg',
        dataType: 'html'
    }).then(function (value) {
        var svg = $(value);
        var width = svg.attr("width");
        var height = svg.attr("height");

    var zoneBounds = [[-height, 0], [0, width]];

    L.imageOverlay('zones.svg', zoneBounds, {
        opacity: 0.5
    }).addTo(mymap);
});

有没有一种方法可以覆盖原始的imageOverlay()方法以接受对象而不是文件的URL? 还是有另一种内置方法?

您可以从VideoOverlay类中汲取一些灵感:扩展ImageOverlay并覆盖_initImage以创建SVG节点而不是图像。

您的课程定义可能如下所示

var SVGOverlay = L.ImageOverlay.extend({
    options: {
    },

    _initImage: function () {
        var wasElementSupplied = this._url.tagName.toLowerCase() === 'svg';
        var svg = this._image = wasElementSupplied ? this._url : L.DomUtil.create('svg');
   }
});

根据您的示例,您可以像这样设置

var svgdomnode = svg.get(0); // your svg looks like a jQuery object, let's use a DOM node
var overlay = new SVGOverlay(svgdomnode, zoneBounds).addTo(mymap);

还有一个演示,其中单击按钮时将SVG节点作为图层插入并进行修改。

 var SVGOverlay = L.ImageOverlay.extend({ options: { }, _initImage: function () { var wasElementSupplied = this._url.tagName.toLowerCase() === 'svg'; var svg = this._image = wasElementSupplied ? this._url : L.DomUtil.create('svg'); } }); var map = L.map('map').setView([37.8, -96], 4); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map); var bounds = L.latLngBounds([[ 32, -130], [ 13, -100]]); map.fitBounds(bounds); var svg = document.getElementById('src').content.querySelector('svg'); var overlay = new SVGOverlay(svg, bounds).addTo(map); var n = 0; document.querySelector('button').addEventListener('click', function() { var rect = document.createElementNS("http://www.w3.org/2000/svg", 'rect'); rect.setAttribute('x', 20*n); rect.setAttribute('width', 20); rect.setAttribute('height', 20); rect.setAttribute('fill', '#0000ff'); svg.appendChild(rect); n++; }); 
 html, body { height: 100%; margin: 0; } #svg { width: 100%; height: 100%; } #map { width: 100%; height: 100%; } button {position: absolute; left:100px; top: 0;z-index:10000} 
 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script> <template id='src'> <svg xmlns="http://www.w3.org/2000/svg" width='100' height='100'> <rect width="100%" height="100%" fill="red"/> <circle cx="50%" cy="50%" r="30%" fill="green"/> </svg> </template> <div id='map'></div> <button>Click to add a square</button> 

1.5.0版将这种方法作为层类型SVGOverlay包括在内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM