OpenLayers:无法向地图添加坐标线串

时间:2019-04-06 15:27:06

标签: javascript openlayers-5

我在显示基于现有坐标列表的线串时遇到麻烦,希望能提供一些帮助。下面是我的代码,该代码显示了OpenLayers5地图,但没有覆盖线串。

我读了很多不同的线程 (OpenLayers 3: simple LineString example)和API文档,但我无法弄清缺少的内容。

map with no linestring overlay

[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
    AssertionOptions.AssertEquivalencyUsing(opt => opt.ComparingByMembers<DataStruct>());
}

JSFiddle link

1 个答案:

答案 0 :(得分:2)

两个错误。首先,它是widthcolor,而不是strokeWidth/Color。其次,您将中心从lon / lat重新投影到WebMercator,但忘了对线坐标进行相同操作-这样您的线实际上位于几内亚湾的某个地方(距0,0点10/50米)。 / p>

这是更正的版本。

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">

    <link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css"
          type="text/css">
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
</head>

<body>
<div id="map" class="map"></div>

<script>
    var view = new ol.View({
        center: ol.proj.fromLonLat([10, 50]),
        zoom: 14
    })

    //Dummy coords
    var coordinates = [
        ol.proj.fromLonLat([10, 50]),
        ol.proj.fromLonLat([11, 51]),
        ol.proj.fromLonLat([12, 55])
    ];

    var layerLines = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: [new ol.Feature({
                geometry: new ol.geom.LineString(coordinates),
                name: 'Line'
            })]
        }),
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#ff0000',
                width: 3
            })
        })
    });

    var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            })
        ],
        view: view
    });

    map.addLayer(layerLines);
</script>

</body>
</html>