1

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]
       })
 );
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);
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.