John Tang
John Tang

Reputation: 23

In openlayers 3, how to fill the polygon with a picture from a url?

I would like to add a picture in the polygon, however, I do not find such function in openlayers 3. Is there any way to achieve this?

Thanks in advance!

Upvotes: 1

Views: 3610

Answers (2)

Jonatas Walker
Jonatas Walker

Reputation: 14150

Since Pull Request #4632 you can use a CanvasRenderingContext2D.fillStyle as ol.style.Fill#color property and create a pattern.

Something like this:

var cnv = document.createElement('canvas');
var ctx = cnv.getContext('2d');
var img = new Image();
img.src = 'https://i.imgsafe.org/73d1273.png';

img.onload = function(){
  var pattern = ctx.createPattern(img, 'repeat');

  // featurePoly is ol.Feature(new ol.geom.Polygon(...))
  featurePoly.setStyle(new ol.style.Style({
    fill: new ol.style.Fill({
      color: pattern
    })
  }));
};

Live demo.

Upvotes: 5

pavlos
pavlos

Reputation: 3081

I am not sure what would be the visual output of your requirement but I may give you the direction to solve your problem.

OL3 can use predifined styles or an array of styles or even a function that returns a style for each feature supplied. So you should propably use the style function to achieve your goal. Lets say that you want to place one image within every vector polygon. Consider the following code snip

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'http://openlayers.org/en/v3.14.0/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature, resolution) {
   var styles = [
    new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#ffcc33',
        width: 2
      }),
      fill: new ol.style.Fill({
      color: 'rgba(255,0,0,0.5)'
      })
    })
  ];
  var mygeomType = feature.getGeometry().getType();
  //handle the case of polygons/multipolygons
  var retGeom = null;
  if (mygeomType === 'MultiPolygon'){
 //get the interior points for every polygon of the multipolygon
  retGeom = feature.getGeometry().getInteriorPoints();
  }
  if (mygeomType === 'Polygon'){
 //just get the interiot point of the simple polygon
  retGeom = feature.getGeometry().getInteriorPoint();
  }
  styles.push(new ol.style.Style({
      geometry: retGeom,
      image: new ol.style.Icon({
        src: 'http://openlayers.org/en/master/examples/data/icon.png',
        anchor: [0.75, 0.5],
        rotateWithView: true
      })
    }));
 return styles;  
}});

check this fiddle to see it in action.

Upvotes: 1

Related Questions