4

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.

Kiran k g
  • 946
  • 11
  • 19

1 Answers1

5

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'
    }))
  });
Alexandre Dubé
  • 2,769
  • 1
  • 18
  • 30
  • 1
    Thank you. If i need to change the position of the overlay that was added earlier i need to use the setposition. But if i have more number of overlays say 50 how can i identify the desired overlay object.Do i need to save the reference of the overlay object and loop through it each time? – Kiran k g Jan 02 '17 at 14:28
  • 2
    Yes, you would need to loop, unless you create a unique id for each overlay and create an object containing them and use the id as key to have a direct access to it (that would avoid the loop). It seems to me that you should go with the layer option, though. – Alexandre Dubé Jan 02 '17 at 14:34