Search code examples
openlayersopenstreetmap

Drawing a route in OpenLayers4 between 2 points


I want to draw a route between 2 points with OpenLayers4.

I know that I should use a polyline to do it, but I don't know how to transform my coordinates in long/lat format to ol.geom.LineString of the polylines

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;

I have a copuple of points, based on coordinates like:

var lat1 = 40.385064;
var lng1 = 2.173403;

var lat2 = 41.385064;
var lng2 = 2.273403;

I took the code from the "Marker Animation" example on the Open Layers website. , because I want to create the polyline based on my 2 points, but I couldn't find any example


Solution

  • If you are asking how to create a line feature from coordinates, this is how you do it.

    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);
    

    And you can add the line feature to your vector layer using vectorLayer.getSource().addFeature(route);