簡體   English   中英

在OpenLayers 4中的兩個坐標之間畫一條線

[英]Draw a line between two coordinates in OpenLayers 4

我想在OpenLayers(OL)4中的兩個坐標之間繪制一條線。我一直在尋找互聯網上的文檔,但大多數僅用於OL 2( example1example2 )或3( example3 )。

我從OL網站上獲取了示例並添加了我自己的代碼。 在這種情況下,我使用LineString:

<!doctype html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.css" type="text/css">
            <style>
          .map {
            height: 400px;
            width: 100%;
          }
            </style>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.js"/>
            <title>OpenLayers example</title>
        </head>
        <body>
            <h2>My Map</h2>
            <div id="map" class="map"/>
            <script type="text/javascript">
                var map = new ol.Map({
                    target: 'map',
                    layers: [
                      new ol.layer.Tile({
                        source: new ol.source.OSM()
                      })
                    ],
                    view: new ol.View({
                      center: ol.proj.fromLonLat([37.41, 8.82]),
                      zoom: 5
                    })
                });

                //example coordinates
                var lonlat = [33.8, 8.4];
                var location2 = [37.5, 8.0];

                //create the line's style
                var linieStyle = [
                            // linestring
                            new ol.style.Style({
                              stroke: new ol.style.Stroke({
                                color: '#d12710',
                                width: 2
                              })
                            })
                          ];

                //create the line       
                var linie = new ol.layer.Vector({
                        source: new ol.source.Vector({
                        features: [new ol.Feature({
                            geometry: new ol.geom.LineString(lonlat, location2),
                            name: 'Line',
                        })]
                    })
                });

                //set the style and add to layer
                linie.setStyle(linieStyle);
                map.addLayer(linie);

            </script>
        </body>
    </html>

但是,該線條不會出現在地圖上。 這是我的JS小提琴 我的代碼中缺少什么?

您需要使用ol.proj.fromLonLat轉換坐標

var lonlat = ol.proj.fromLonLat([33.8, 8.4]);
var location2 = ol.proj.fromLonLat([37.5, 8.0]);

您還需要為new ol.geom.LineString提供一系列點

new ol.geom.LineString([lonlat, location2])

您可以使用基於Js Fiddle 的修復程序查看我的派生示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM