Bill Bill - 3 months ago 110
Javascript Question

Make marker zoom/rotate with map in Openlayers 3

I'm trying to overlay an image over an OpenLayers 3.0 map by adding a point feature to the layer, and setting the icon to the image to load. How can I get it to scale with the map as it is being zoomed?
Or is there a better way to overlay an image atop a layer?

p=ol.proj.transform( [-78,40],'EPSG:4326','EPSG:3857')
var f=new ol.Feature({ geometry: new ol.geom.Point(p) });

var imgStyle=new ol.style.Style({
image: new ol.style.Icon(({
rotateWithView: false,
anchor: [.5,.5],
anchorXUnits: 'fraction', anchorYUnits: 'fraction',
opacity: 0.75,
src: 'http://www.viseyes.org/shiva/map.jpg'
}))
});

f.setStyle(imgStyle);
myLayerr.getSource().addFeature(f);

Answer

It looks like you are trying to use an image of a map as an overlay. Instead of using the image as an icon for a feature with a point geometry, you'd be better off using an image layer with a static image source. See the code below for an example (also http://jsfiddle.net/tschaub/orr6qfkc/).

var extent = ol.proj.transformExtent(
    [-5.6342, 50.3331, 1.6607, 53.0559], 'EPSG:4326', 'EPSG:3857');

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'osm'})
    }),
    new ol.layer.Image({
      source: new ol.source.ImageStatic({
        url: 'http://www.viseyes.org/shiva/map.jpg',
        imageExtent: extent
      })
    })
  ],
  view: new ol.View({
    center: ol.extent.getCenter(extent),
    zoom: 7
  })
});

I've just guessed at the geographic extent of the image. It may also be that the image overlays better on a map with the view projection set to 'EPSG:4326'.

Note that if you want to use an icon to symbolize a point feature and you want it to rotate and scale with the map (as the title of this question implies), you need to do two things:

  • Set the rotateWithView option to true (the default of false means that the icon will not rotate when you rotate the map).
  • Give your vector layer a style function. This function will be called with your feature and the view resolution. You can then scale your icon using the resolution. The style function below should give you a rough idea of how this could work.
// resolution at which to display the
// icon at 1:1
var maxResolution = 10000;

function style(feature, resolution) {
  var icon = new ol.style.Style({
    image: new ol.style.Icon({
      src: 'http://example.com/icon.png',
      scale: maxResolution / resolution,
      rotateWithView: true
    }))
  });
  return [symbolizer];
}