How to Draw a line string between two points (coordinates) in open layers

How to Draw a line string between two points (coordinates) in open layers

by Prashant Ujjainkar

HTML

<script src="https://cdn.jsdelivr.net/npm/ol@v7.1.0/dist/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v7.1.0/ol.css">
 <div id="map" style="width: 100%; height:1000px"></div>

JavaScript

var coords = [[79.0882,21.1458], [73.8567, 18.5204]];


var lineString = new ol.geom.LineString(coords);
// transform to EPSG:3857
lineString.transform('EPSG:4326', 'EPSG:3857');

// create the feature
var feature = new ol.Feature({
    geometry: lineString,
    name: 'Line'
});

var lineStyle = new ol.style.Style({
    stroke: new ol.style.Stroke({
        color: '#0062ff',
        width: 2
    })
});

var source = new ol.source.Vector({
	features: [feature]
});
var vector = new ol.layer.Vector({
	source: source,
	style: [lineStyle]
});

        var view = new ol.View({
              center: ol.proj.transform([77.3210,19.1383], 'EPSG:4326', 'EPSG:3857'),
              zoom: 7
            }) 


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