JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css">
<div id="info"></div>
<div id="map"></div>
CSS
#map {
width: 100%;
height: 400px;
}
#info {
margin-bottom: 10px;
padding: 0 5px 0 35px;
font-family: sans-serif;
font-size: 16px;
line-height: 2;
background-color: rgb(66, 99, 132);
color: rgb(255, 255, 255);
position: relative;
}
#info::before {
width: 14px;
height: 14px;
margin-top: -7px;
position: absolute;
top: 50%;
left: 10px;
content: 'i';
font-size: 10px;
line-height: 14px;
text-align: center;
background-color: rgb(255, 255, 255);
border-radius: 50%;
color: rgb(66, 99, 132);
}
JavaScript
window.phpdata = {};
Object.defineProperty(window.phpdata, "markers", {value: [{"lng":"-74.0061","lat":"40.712","info":"Marker #1"},{"lng":"40.712","lat":"40.712","info":"Marker #2"},{"lng":"19.291","lat":"50.712","info":"Marker #3"}], writable: false, configurable: false});
var base = new ol.layer.Tile({
source: new ol.source.OSM()
});
var view = new ol.View({
center: ol.proj.fromLonLat([-74.0061,40.712]),
zoom: 2
})
var map = new ol.Map({
target: 'map',
layers: [base],
view: view
});
var vectors = new ol.source.Vector({});
var doticon = new ol.style.Style({
image: new ol.style.Icon({
anchor: [20, 20],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
src: 'https://raw.githubusercontent.com/itsmohitt/openlayers-tutorials/master/dot.png'
})
});
if(window.phpdata.markers && window.phpdata.markers.length > 0) {
var data = window.phpdata.markers;
for(var i = 0; i < data.length; i++) {
var marker = new ol.Feature({
geometry: new ol.geom.Point(
ol.proj.fromLonLat([Number(data[i].lng), Number(data[i].lat)])
),
info: data[i].info
});
marker.setStyle(doticon);
vectors.addFeature(marker);
}
}
var layer = new ol.layer.Vector({
source: vectors,
});
map.addLayer(layer);
map.on('click', function(event) {
var feature = map.forEachFeatureAtPixel(event.pixel, function(feature) { return feature; });
var infobox = document.querySelector('#info');
infobox.innerText = feature ? feature.get('info') : '';
});