在OpenLayers中使用HTML5呈现本地文件

时间:2013-05-23 09:20:42

标签: html5 canvas svg openlayers

有一些HTML5的FileSystem,FileAccess功能的例子,用户可以添加文件而不发送到服务器端。

我正在使用OpenLayers开发一个地图应用程序,我希望添加此功能,用户可以拖放kml文件或从对话框中选择kml文件,并在本地添加到地图。

OpenLayers可以实现这种行为吗?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:2)

摘自此演示:

http://jsfiddle.net/AbdiasSoftware/t42cu/

(小提琴更新了扩展程序和文件大小检查)。

在html中定义一个放置区域:

<div id="fileDrop">Drop KML file here</div>

根据需要设置样式:

#fileDrop {
    padding:20px;
    text-align:center;
    border:3px dashed #777;
    border-radius:12px;
    opacity:0.5;
    color:#fff;
    }
#fileDrop:hover {
    background-color:rgba(255,255,255,0.7);
    }

要启用拖放文件,您可以使用以下代码:

var fileDrop = document.getElementById('fileDrop');
fileDrop.addEventListener('dragover', fileDragOver, false);
fileDrop.addEventListener('drop', fileSelect, false);

// change style of the drop area when file is over
function fileDragOver(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
}

//load file on drop
function fileSelect(e) {

    e.stopPropagation();
    e.preventDefault();

    var files = e.dataTransfer.files,
        f = files[0],
        reader,

        fname = f.name.toLowerCase(),
        fsize = f.size,

        maxSize = 1024 * 1024; // 1mb

    /// Check file extension and file size
    if (fname.length < 5 || fname.substring(fname.length - 4) !=='.kml') {
        alert('Need a .kml file!');
        return;
    }

    if (fsize > maxSize) {
        alert('File is too big!');
        return;
    }

    reader = new FileReader(),

    reader.onload = function(fe) {

        var kml = fe.target.result; // the file
        gotoOpenLayer(kml);

    }
    reader.readAsText(f);
}

gotoOpenLayer函数中,我们将文件转换为Blob,然后转换为objectURL

function gotoOpenLayer(kml) {

    var blob = new Blob([kml], {type: 'text/plain'});
    var lnk = window.URL.createObjectURL(blob);

    /// pass in lnk as url or kml as string to OpenLayers

    // ....
}

我找到了网址加载和传递字符串的示例。

使用Blob网址 -

var map = new OpenLayers.Map({
    div: "map",
    layers: [
        new OpenLayers.Layer.WMS(
            "WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0",
            {layers: "basic"}
        ),
        new OpenLayers.Layer.Vector("KML", {
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({

                url: lnk, /// url goes here

                format: new OpenLayers.Format.KML({
                    extractStyles: true, 
                    extractAttributes: true,
                    maxDepth: 2
                })
            })
        })
    ],
    center: new OpenLayers.LonLat(-112.169, 36.099),
    zoom: 11
});

或者将加载的文件作为字符串传递:

function getFeaturesFromKMLString (kml) {
    var format = new OpenLayers.Format.KML({
        'internalProjection': myMapObject.baseLayer.projection,
        'externalProjection': new OpenLayers.Projection("EPSG:4326")
    });
    return format.read(kml);
};

// ...
myVectorLayer.addFeatures(getFeaturesFromKMLString(kml));