JSFiddle - React, Tailwind, and code Playground
by Jonathan
HTML
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.15.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.15.1/build/ol.js"></script>
<title>OpenLayers example</title>
</head>
<div id="map" class="map"></div>
JavaScript
const extent = [-400, -85, 400, 85]
const textent = ol.proj.transformExtent(
extent,
"EPSG:4326",
"EPSG:3857"
)
const canvas = document.createElement("canvas");
const vsource = new ol.source.Vector({ wrapX: false });
const vlayer = new ol.layer.Vector({source: vsource})
const points = [[extent[0],0], [extent[0] + 100,0]].map(p => ol.proj.transform(p, "EPSG:4326", "EPSG:3857"))
const points2 = [[-50,0], [0,0]].map(p => ol.proj.transform(p, "EPSG:4326", "EPSG:3857"))
vsource.addFeature(new ol.Feature(new ol.geom.LineString(points)))
vsource.addFeature(new ol.Feature(new ol.geom.LineString(points2)))
vlayer.on('postrender', () => {
var ctx = vlayer.getRenderer().context;
for (let f of vsource.getFeatures()) {
const coords = f.getGeometry().getCoordinates();
const pixel1 = this.map.getPixelFromCoordinate(coords[0]);
const pixel2 = this.map.getPixelFromCoordinate(coords[1]);
ctx.save();
ctx.beginPath();
ctx.moveTo(pixel1[0],pixel1[1] );
ctx.lineTo(pixel2[0],pixel2[1]);
ctx.closePath();
ctx.strokeStyle = "red";
ctx.stroke()
ctx.restore()
}
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vlayer,
],
view: new ol.View({
projection: "EPSG:3857",
minZoom: 2.75,
center: ol.proj.transform([-10,-5],"EPSG:4326","EPSG:3857"),
zoom: 5,
extent:textent
}),
});