首页 > 解决方案 > OpenLayers:无法将坐标线串添加到地图

问题描述

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

我已经阅读了许多不同的线程(OpenLayers 3:简单的 LineString 示例)和 API 文档,但我无法弄清楚我所缺少的内容。

没有线串叠加的地图

<!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 type="text/javascript">   
    var view = new ol.View({
      center: ol.proj.fromLonLat([10,50]),
      zoom: 14
    })

    //Dummy coords
    var coordinates = [
      [10, 50],
      [11, 51],
      [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({ 
            strokeColor: '#ff0000',
            strokeWidth: 5                      
          })
        })
    });

    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>

JSFiddle 链接

标签: javascriptopenlayers-5

解决方案


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

这是更正的版本。

<!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>


推荐阅读