在OpenLayers4中绘制2点之间的路线

时间:2018-06-13 07:11:11

标签: openlayers openstreetmap

我想用OpenLayers4绘制2点之间的路线。

我知道我应该使用折线来做,但我不知道如何将长/纬格式的坐标转换为折线的ol.geom.LineString

var polyline = [
        'hldhx@lnau`BCG_EaC??cFjAwDjF??uBlKMd@}@z@??aC^yk@z_@se@b[wFdE??wFfE}N',
        'fIoGxB_I\\gG}@eHoCyTmPqGaBaHOoD\\??yVrGotA|N??o[N_STiwAtEmHGeHcAkiA}^',
        'aMyBiHOkFNoI`CcVvM??gG^gF_@iJwC??eCcA]OoL}DwFyCaCgCcCwDcGwHsSoX??wI_E',
        'kUFmq@hBiOqBgTwS??iYse@gYq\\cp@ce@{vA}s@csJqaE}{@iRaqE{lBeRoIwd@_T{]_',
        'Ngn@{PmhEwaA{SeF_u@kQuyAw]wQeEgtAsZ}LiCarAkVwI}D??_}RcjEinPspDwSqCgs@',
        'sPua@_OkXaMeT_Nwk@ob@gV}TiYs[uTwXoNmT{Uyb@wNg]{Nqa@oDgNeJu_@_G}YsFw]k',
        'DuZyDmm@i_@uyIJe~@jCg|@nGiv@zUi_BfNqaAvIow@dEed@dCcf@r@qz@Egs@{Acu@mC',
        'um@yIey@gGig@cK_m@aSku@qRil@we@{mAeTej@}Tkz@cLgr@aHko@qOmcEaJw~C{w@ka',
        'i@qBchBq@kmBS{kDnBscBnFu_Dbc@_~QHeU`IuyDrC_}@bByp@fCyoA?qMbD}{AIkeAgB',
        'k_A_A{UsDke@gFej@qH{o@qGgb@qH{`@mMgm@uQus@kL{_@yOmd@ymBgwE}x@ouBwtA__',
        'DuhEgaKuWct@gp@cnBii@mlBa_@}|Asj@qrCg^eaC}L{dAaJ_aAiOyjByH{nAuYu`GsAw',


        'uEeFymAssAkdAmhAyTcVkFeEoKiH}l@kp@wg@sj@ku@ey@uh@kj@}EsFmG}Jk^_r@_f@m',
        '~@ym@yjA??a@cFd@kBrCgDbAUnAcBhAyAdk@et@??kF}D??OL'
      ].join('');

      var route = /** @type {ol.geom.LineString} */ (new ol.format.Polyline({
        factor: 1e6
      }).readGeometry(polyline, {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:3857'
      }));

      var routeCoords = route.getCoordinates();
      var routeLength = routeCoords.length;

我有一个基于以下坐标的点的聚集:

var lat1 = 40.385064;
var lng1 = 2.173403;

var lat2 = 41.385064;
var lng2 = 2.273403;

我从Open Layers网站上的“Marker Animation”示例中获取了代码。 ,因为我想根据我的2点创建折线,但我找不到任何示例

1 个答案:

答案 0 :(得分:1)

如果您询问如何从坐标创建线要素,则按照这种方式进行操作。

var route = new ol.Feature();
var coordinates = [[2.173403, 40.385064], [2.273403,41.385064]];
var geometry = new ol.geom.LineString(coordinates);
geometry.transform('EPSG:4326', 'EPSG:3857'); //Transform to your map projection
route.setGeometry(geometry);

您可以使用vectorLayer.getSource().addFeature(route);

将线要素添加到矢量图层