Is there any way that I can create a marker in OpenLayers with an HTML icon?
Example in Mapbox:
marker.setIcon(
L.divIcon({
className: 'map_primary_marker_container',
html: "<div class='map_primary_marker'>TEXT</div><div class='map_primary_marker_bottom'></div>",
iconSize: [160, 50],
iconAnchor: [80, 40]
})
);
nmtoken
13.6k5 gold badges39 silver badges91 bronze badges
asked Aug 24, 2017 at 15:30
1 Answer 1
I found myself a solution, it's a tricky one but if anyone has a better idea please answer.
//options object
var options = {
className: 'map_primary_marker_container',
html: "<div class='map_primary_marker'>TEXT</div><div class='map_primary_marker_bottom'></div>",
iconSize: [160, 50],
iconAnchor: [80, 40]
};
// create a container for the html code and set the properties
var div = document.createElement('div');
div.className = options.className;
div.style.position = 'absolute';
div.style.width = options.iconSize[0] + 'px';
div.style.height = options.iconSize[1] * 10 + 'px';
div.innerHTML = options.html;
var element = document.body.appendChild(div);
// generate an encoded picture from the element
html2canvas(element,{
onrendered: function (canvas){
setTimeout(function () {
marker.setStyle(new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [options.iconAnchor[0], options.iconAnchor[1]],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
src: canvas.toDataURL()
}))
}));
}, 50);
element.parentNode.removeChild(element);
}
});
answered Aug 24, 2017 at 17:53
lang-js