在OpenLayers 3中使用编码折线

时间:2015-07-07 18:26:34

标签: javascript openlayers-3

我在尝试在OpenLayers 3中使用编码折线时遇到了麻烦。我有一个提供编码字符串的外部源,但是当我尝试将它们转换为特征并将它们添加到矢量源时,我收到以下错误:

Uncaught TypeError: Cannot read property 'ua' of undefined

以下是我正在使用的当前代码:

vectorSource = new ol.source.Vector();
var layers = [
    new ol.layer.Tile({
        name: "SKL Tile Server",
        source: new ol.source.OSM({
            url: "https://placeholder/osm/{z}/{x}/{y}.png",
            crossOrigin: null
        })
    }),
    new ol.layer.Vector({
        name: "polylines",
        source: vectorSource
    })
];

map = new ol.Map({
    layers: layers,
    target: 'report_map',
    view: new ol.View({
        center: ol.proj.transform(
            [-118.014670, 45.35724], 'EPSG:4326', 'EPSG:900913'),
        zoom: 10
    })
})

var addPolylineToMap = function (encoded_line, line_style) {

    var line = new ol.format.Polyline().readGeometry({
        source: encoded_line,
        options: {
            dataProjection: ol.proj.get('EPSG:4326'),
            featureProjection: ol.proj.get('EPSG:900913')
        }
    });
    line.setStyle(line_style);
    vectorSource.addFeature(new ol.Feature(line));
    return line;
};

不可否认,我对OpenLayers 3很陌生 - 但我已经进行了广泛的搜索,似乎无法在OpenLayers 3中找到任何使用编码折线的例子。

1 个答案:

答案 0 :(得分:4)

尝试这种方式:

var addPolylineToMap = function (encoded_line, line_style) {

    var format = new ol.format.Polyline({
        //factor: 1e6
    });
    var line = format.readGeometry(encoded_line, {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:900913'
    });

    var feature = new ol.Feature({geometry: line});
    feature.setStyle(line_style);
    vectorSource.addFeature(feature);

    return line;
};