JSFiddle - React, Tailwind, and code Playground
by chudnovskym
HTML
<script src="https://cdn.jsdelivr.net/npm/ol@v7.2.2/dist/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v7.2.2/ol.css">
<div id="map" class="map"></div>
<div id="info" class="info">
<h2>Map Info Output (Lon / Lat)</h2>
Center: <span id=center></span><br>
Marker: <span id=marker></span><br>
<span id=update>*update if the marker is on the map or not here.</span>
</div>
CSS
#map{
width: 300px;
height: 300px;
border: 1px solid black;
padding: 5px;
float: left;
}
#info{
width: calc(100% - 330px);
margin-left: 5px;
padding: 5px;
height: 100px;
border: 1px solid black;
float: left;
}
.info h2{
font-size: small;
text-decoration: underline;
font-weight: 600;
margin: 0 0 10px 0;
}
JavaScript
var london = [-0.1276474, 51.507321899999994];
var isOnMap = true;
document.getElementById('marker').innerHTML = london[0].toFixed(3) + ", " + london[1].toFixed(3);
document.getElementById('center').innerHTML = london[0].toFixed(3) + ", " + london[1].toFixed(3);
const baseMapTile = new ol.layer.Tile({
source: new ol.source.OSM(),
visible: true,
title: 'OSMStandard'
});
const marker = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat(london)),
name: 'Somewhere near Nottingham',
});
const map = new ol.Map({
view: new ol.View({
center: (ol.proj.fromLonLat(london)),
zoom: 15,
}),
layers: [
baseMapTile,
new ol.layer.Vector({
source: new ol.source.Vector({
features: [marker]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'https://openlayers.org/en/latest/examples/data/icon.png'
})
})
})
],
target: 'map'
});
var translate = new ol.interaction.Translate({
features: new ol.Collection([marker])
});
map.addInteraction(translate);
translate.on('translating', function (evt) {
var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
document.getElementById("marker").innerHTML = lonlat[0].toFixed(3) + ", " + lonlat[1].toFixed(3);
//check here to see if marker is still visible on map and update output
});
map.getView().on(['change:center', 'change:resolution', 'change:rotation'], function() {
var center = ol.proj.transform(map.getView().getCenter(), 'EPSG:3857', 'EPSG:4326');
document.getElementById("center").innerHTML = center[0].toFixed(3) + ", " + center[1].toFixed(3);
//check here to see if marker is still visible on map and update output
});