Search code examples
openlayers-3custom-elementcustom-overlay

How to add Custom Html dom element in layers of Openlayer 3


I have used Google api Overlayviews. I was able to add custom overlays with html div element at a latlng position using the pixel values.

USGSOverlay.prototype.draw = function() {
var overlayProjection = this.getProjection();
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
 div.style.height = (sw.y - ne.y) + 'px';
      };

Now i am using OpenLayer 3. Is there any option to add a custom div element like a marker at a particular position using pixel values. Each time when the map is zoomed in or zoomed out i can find the pixel position and update the top and left of the div element so that it appears to be at the correct position.Is there any possibility for this in OpenLayer3.


Solution

  • If you want to show plain HTML at a specific location in ol3, use a ol.Overlay. See the ol3 overlay example. You can control the content in plain HTML and style in CSS.

      // Vienna marker
      var marker = new ol.Overlay({
        position: pos,
        positioning: 'center-center',
        element: document.getElementById('marker'),
        stopEvent: false
      });
      map.addOverlay(marker);
    

    If you have to do this for multiple locations, let's say more than 10, and you only need to show some sort of marker, then I'd recommend using a ol.layer.Vector instead with the proper style object. See the ol3 icon example. You could use any image for your marker. You can also control its positionning.

      var iconStyle = new ol.style.Style({
        image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
          anchor: [0.5, 46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          src: 'https://openlayers.org/en/v3.20.1/examples/data/icon.png'
        }))
      });