Trying to change radius of circle using html 5 range slider but its not removing 1st circle layer but map.removeLayer not working I done this befor using openlayer 2 but its not working with openlayer 3 I added the code.
Working copy of openlayer 2
Need same in open layer 3 below is the code
IMP - Required range of slider from 1 miles to 5 miles
var features = [];
var radius = $('#range').val();
var longitude = 400000;
var latitude = 300000;
var point1 = new ol.Feature(
new ol.geom.Point([400000, 400000])
);
//console.log(point1);
//alert(radius);
//var point1 = new ol.geom.Point(400000,400000);
var circle = new ol.geom.Circle([longitude, latitude], radius);
features.push(new ol.Feature({
geometry: circle
}));
var circleSource = new ol.source.Vector({
features: features
});
var layer = new ol.layer.Vector({
source: circleSource,
style: [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
})]
});
// create map
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: [400000, 300000],
zoom: 2
})
});
map.addLayer(layer);
function updateTextInput(val) {
document.getElementById('range').value=val;
radius = $( "#range" ).val();
console.log(radius);
map.removeLayer(layer);
// increaseRadius(30000);
var features = [];
//var radius = 100000;
var longitude = 400000;
var latitude = 300000;
var point1 = new ol.Feature(
new ol.geom.Point([400000, 400000])
);
//alert(radius);
//var point1 = new ol.geom.Point(400000,400000);
var circle = new ol.geom.Circle([longitude, latitude], radius);
features.push(new ol.Feature({
geometry: circle
}));
var circleSource = new ol.source.Vector({
features: features
});
var layer = new ol.layer.Vector({
source: circleSource,
style: [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
})]
});
map.addLayer(layer);
}
html, body {
height:100%;
width: 100%;
padding:5px;
margin:0px;
}
#map {
height:90%;
width: 95%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.5.0/ol.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.5.0/ol.js"></script>
<div>
<input type="range" class="slider" name="rangeInput" min="1" max="5" onchange="updateTextInput(this.value);">
<input type="text" id="range" value="1">
</div>
<div id="map"></div>
You can just change the ol.Feature#setStyle style like:
// we change this on input change
var radius = 10;
var styleFunction = function() {
return new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
stroke: new ol.style.Stroke({
color: [51, 51, 51],
width: 2
}),
fill: new ol.style.Fill({
color: [51, 51, 51, .3]
})
})
});
};
var update = function(value) {
radius = value;
feature.setStyle(styleFunction);
}
var feature = new ol.Feature(new ol.geom.Point([400000, 400000]));
feature.setStyle(styleFunction);
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [feature]
})
});
[Demo]
you don't have to remove the layer and add a new one if you want to modify the radius of you circle, you can simply use :
yourCircle.setRadius(yourNewRadius);
and make sure you are using the latest version of OL3 since this function is still experimental
Related
I am working with openlayers 6 and I need to draw clouds on the maps a polygon with half circles stroke or a linestring, it doesn't matter the type as long as I can modify it ( adding and removing points, stretching, shrinking it). My knowledge of Openlayers is very limited so I am asking for guidance, how can I possibly do that
You could use a custom style which changes the displayed geometry, similar to https://openlayers.org/en/latest/examples/polygon-styles.html but replacing the segments of the polygon ring with semi-circular arcs.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.14.1/css/ol.css" type="text/css">
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.14.1/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector({wrapX: false});
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
}),
geometry: function (feature) {
var geometry = feature.getGeometry();
if (geometry.getType() === 'Polygon') {
var coordinates = geometry.getCoordinates(true)[0];
var arcs = [];
for (let i = 0, len = coordinates.length - 1; i < len; ++i) {
var center = [
(coordinates[i + 1][0] + coordinates[i][0]) / 2,
(coordinates[i + 1][1] + coordinates[i][1]) / 2
];
var dx = coordinates[i + 1][0] - coordinates[i][0];
var dy = coordinates[i + 1][1] - coordinates[i][1];
var radius = Math.sqrt(dx * dx + dy * dy) / 2;
var angle = Math.atan2(-dy, -dx);
var sides = 32;
arcs = arcs.concat(
ol.geom.Polygon.fromCircle(
new ol.geom.Circle(center, radius),
sides,
angle
).getCoordinates(true)[0].slice(0, sides / 2)
);
}
return new ol.geom.Polygon([arcs.concat([arcs[0]])]);
} else {
return geometry;
}
}
});
var vector = new ol.layer.Vector({
source: source,
style: style
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var modify = new ol.interaction.Modify({source: source});
map.addInteraction(modify);
var draw = new ol.interaction.Draw({
source: source,
type: 'Polygon',
style: style
});
map.addInteraction(draw);
var snap = new ol.interaction.Snap({source: source});
map.addInteraction(snap);
</script>
</body>
</html>
Second example with elliptical arcs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.14.1/css/ol.css" type="text/css">
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.14.1/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector({wrapX: false});
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
}),
geometry: function (feature) {
var geometry = feature.getGeometry();
if (geometry.getType() === 'Polygon') {
var coordinates = geometry.getCoordinates(true)[0];
var arcs = [];
for (let i = 0, len = coordinates.length - 1; i < len; ++i) {
var center = [
(coordinates[i + 1][0] + coordinates[i][0]) / 2,
(coordinates[i + 1][1] + coordinates[i][1]) / 2
];
var dx = coordinates[i + 1][0] - coordinates[i][0];
var dy = coordinates[i + 1][1] - coordinates[i][1];
var radius = Math.sqrt(dx * dx + dy * dy) / 2;
var angle = Math.atan2(-dy, -dx);
var sides = 32;
var circle = ol.geom.Polygon.fromCircle(
new ol.geom.Circle(center, radius),
sides,
angle
);
circle.rotate(-angle, center);
circle.scale(1, 0.5, center);
circle.rotate(angle, center);
arcs = arcs.concat(
circle.getCoordinates(true)[0].slice(0, sides / 2)
);
}
return new ol.geom.Polygon([arcs.concat([arcs[0]])]);
} else {
return geometry;
}
}
});
var vector = new ol.layer.Vector({
source: source,
style: style
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var modify = new ol.interaction.Modify({source: source});
map.addInteraction(modify);
var draw = new ol.interaction.Draw({
source: source,
type: 'Polygon',
style: style
});
map.addInteraction(draw);
var snap = new ol.interaction.Snap({source: source});
map.addInteraction(snap);
</script>
</body>
</html>
In my app I wrote an ol.interaction.Draw code that allow me to draw a circle everytime I click on one map panel, and this circle work good for me because I can move, rotate and rescale proportionally it. This is my code:
map.addInteraction(new ol.interaction.Modify({
features: this.features,
deleteCondition: function (event) {
return ol.events.condition.shiftKeyOnly(event) && ol.events.condition.singleClick(event);
}
}));
this.draw = new ol.interaction.Draw({
features: this.features,
type: 'Circle',
draggable:true;
});
this.draw.on('drawstart', function () {
this.features.clear();
}, this);
this.map.addInteraction(this.draw);
But I would like to draw an image (e.g. with the source media/image/landscape.png), instead of one circle, but with the same features (drag and drop, rotate, rescale proportionally). How I could do it?
You would probably want to draw circles but style them using your png as an icon. Scaling would be based on the circle radius. Circle geometry doesn't include rotation but by using a geometryFunction in the interaction you could set a rotation and use that to rotate the icon (the angle needs to be adjusted depending on which edge or corner of the icon is used for the rotation).
var white = [255, 255, 255, 1];
var blue = [0, 153, 255, 1];
var width = 3;
styles = [
new ol.style.Style({
fill: new ol.style.Fill({
color: [255, 255, 255, 0.5]
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: white,
width: width + 2
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: blue,
width: width
})
}),
new ol.style.Style({
image: new ol.style.Circle({
radius: width * 2,
fill: new ol.style.Fill({
color: blue
}),
stroke: new ol.style.Stroke({
color: white,
width: width / 2
})
}),
zIndex: Infinity
})
];
var treeStyle = new ol.style.Style({
image: new ol.style.Icon({
src: 'https://www.freeiconspng.com/uploads/oak-tree-icon-png-17.png'
})
});
styleFunction = function(feature, resolution) {
if (feature.getGeometry().getCenter) {
treeStyle.setGeometry(new ol.geom.Point(feature.getGeometry().getCenter()));
treeStyle.getImage().setRotation(feature.getGeometry().get('rotation'));
treeStyle.getImage().setScale(feature.getGeometry().getRadius()/(150*resolution));
return treeStyle;
} else {
return styles;
}
}
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector({wrapX: false});
var vector = new ol.layer.Vector({
source: source,
style: styleFunction
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var draw = new ol.interaction.Draw({
source: source,
type: 'Circle',
geometryFunction: function(coordinates, geometry) {
var center = coordinates[0];
var last = coordinates[1];
var dx = center[0] - last[0];
var dy = center[1] - last[1];
var radius = Math.sqrt(dx * dx + dy * dy);
var rotation = Math.PI - Math.atan2(dy, dx);
geometry = geometry || new ol.geom.Circle(center, radius);
geometry.setCenter(center);
geometry.setRadius(radius);
geometry.set('rotation', rotation);
return new ol.geom.Circle(center, radius);
},
style: styleFunction
});
map.addInteraction(draw);
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>
I dynamically add features to my cluster, however, as far as I can see clustering does not work. My layer is defined like so:
var source = new ol.source.Vector({});
var cluster = new ol.source.Cluster({
distance: 10,
source: source
});
var style = new ol.style.Style({
fill: new ol.style.Fill({
color: "rgba(255,150,0,1)"
}),
stroke: new ol.style.Stroke({
color: "rgba(255,150,0,1)",
width: 1
}),
image: new ol.style.Circle({
radius: 1,
fill: new ol.style.Fill({
color: "rgba(255,150,0,1)"
})
}),
zIndex: 1
});
var layer = new ol.layer.Vector({
source: cluster,
style: style,
zIndex: 1
});
And I add multiple features (Point geometries) in bulk in one of my functions, which take the layer as an argument. It does it like so:
layer.getSource().clear();
layer.setVisible(true);
layer.getSource().addFeatures(features); // features is a large array of features
However, if I zoom in and zoom out, I see these pictures:
and:
On the second screen shot, you can see, that my layer shows all features and ignores clustering parameter. Why is that and how can I fix it? (PS. If it matters, I'm using the latest version of OL)
this is working fine, i updates this example with your code and added features with random values
openlayers.org/en/latest/examples/cluster.html
<!DOCTYPE html>
<html>
<head>
<title>Clustered Features</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<form>
<label>cluster distance</label>
<input id="distance" type="range" min="0" max="100" step="1" value="40"/>
</form>
<script>
var distance = document.getElementById('distance');
var source = new ol.source.Vector({
});
var cluster = new ol.source.Cluster({
distance: 10,
source: source
});
var style = new ol.style.Style({
fill: new ol.style.Fill({
color: "rgba(255,150,0,1)"
}),
stroke: new ol.style.Stroke({
color: "rgba(255,150,0,1)",
width: 1
}),
image: new ol.style.Circle({
radius: 1,
fill: new ol.style.Fill({
color: "rgba(255,150,0,1)"
})
}),
zIndex: 1
});
var clusters = new ol.layer.Vector({
source: cluster,
style: style,
zIndex: 1
});
var map = new ol.Map({
layers: [clusters],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var count = 20000;
var features = new Array(count);
var e = 4500000;
for (var i = 0; i < count; ++i) {
var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
/*features[i] =*/ source.addFeature(new ol.Feature(new ol.geom.Point(coordinates)));
}
distance.addEventListener('input', function() {
cluster.setDistance(parseInt(distance.value, 10));
});
</script>
</body>
</html>
Good Luck
I was recently tasked with creating the map for my Wurm Online game alliance. I crafted a genius SVG-based overlay over a static image of an in-game map. Basically it takes data from a spreadsheet and renders Villages as colored circles on the map.
However, we have members all the over the map, so went about to seeing how I could create a zoom-able web-based map of our lands. The game admins give us a map dump every year or thereabouts, so we can create custom map applications however we feel. I downloaded the recent map dump for the island/server I care about, Xanadu.
The Xanadu dump is a 62MB PNG with a resolution of 8192 x 8192 pixels. I found a tile making program (MapTiler version 7), and I went about creating tiles. After the tiles are done rendering, the program itself creates HTML files with embedded JavaScript all programatically. It gave me a head start with OpenLayers3.
I was able to re-calculate Village coordinates and cobble together a zoom-able tiled map with Village circles. Needless to say, I was very happy when I got my custom OpenLayers3 map. (Working example: http://jackswurmtools.com/Content/Static/map.html)
The way I got it set up, each map "decoration" or colored circle is its own Vector.
The chief complaint from my fellow gamers about my zoom-able map, is that the color Village circles are too big zoomed out, yet too small when zoomed in.
I've tried all kinds of things, but I have yet to find the right examples. I'm used to finding and transforming SVG elements based on events, but the OP3 canvas rendering is NOT obvious to me in the DOM.
Some of my questions are:
How can I detect when my map has been zoomed? Is there some callback I'm missing?
And when a zoom is detected, how can I iterate through all my vectors and update a circle radius.
// jacks fully zoomable xanadu map
var data =
[{
X: "6744",
Y: "-2355.75",
Name: "Amish Creek",
Villagers: ["Aniceset", "Fulano"],
BackColor: "Aquamarine",
LandMarkType: "Member"
}, {
X: "6808.75",
Y: "-2265.125",
Name: "Amish Estates",
Villagers: ["Aniceset", "Villagers"],
BackColor: "Purple",
LandMarkType: "Member"
}];
console.log(data);
var mapExtent = [0.00000000, -8192.00000000, 8192.00000000, 0.00000000];
var mapMinZoom = 0;
var mapMaxZoom = 5;
var mapMaxResolution = 1.00000000;
var tileExtent = [0.00000000, -8192.00000000, 8192.00000000, 0.00000000];
var mapResolutions = [];
for (var z = 0; z <= mapMaxZoom; z++) {
mapResolutions.push(Math.pow(2, mapMaxZoom - z) * mapMaxResolution);
}
var mapTileGrid = new ol.tilegrid.TileGrid({
extent: tileExtent,
minZoom: mapMinZoom,
resolutions: mapResolutions
});
var features = [];
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
projection: 'PNGMAP',
tileGrid: mapTileGrid,
url: "http://jackswurmtools.com/Content/Static/{z}/{x}/{y}.png"
})
}),
],
view: new ol.View({
zoom: 4,
center: [6602.375, -2250.3125],
projection: ol.proj.get('PNGMap'),
maxResolution: mapTileGrid.getResolution(mapMinZoom)
}),
});
map.getView();
map.on('singleclick', function(evt) {
var coord = evt.coordinate;
console.log(coord);
$("#coord-overlay").html("[" + coord[0] + ", " + coord[1] + "]");
});
// zoom stuff?
// add layers via JSON iteration
renderSVG(data);
drawLines();
function renderSVG(data) {
var vectorSource = new ol.layer.Vector({});
console.log(map.getView().getZoom());
jQuery.each(data, function() {
var fill = new ol.style.Fill({
color: this.BackColor
});
var stroke = new ol.style.Stroke({
color: [180, 0, 0, 1],
width: 1
});
var style = new ol.style.Style({
image: new ol.style.Circle({
fill: fill,
stroke: stroke,
radius: map.getView().getZoom() * 5,
opacity: 0.7
}),
fill: fill,
stroke: stroke,
text: new ol.style.Text({
font: '12px helvetica,sans-serif',
text: this.Name,
fill: new ol.style.Fill({
color: '#000'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
});
var point_feature = new ol.Feature({});
var point_geom = new ol.geom.Point([this.X, this.Y]);
point_feature.setGeometry(point_geom);
var vector_layer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [point_feature],
})
});
vector_layer.setStyle(style);
map.addLayer(vector_layer);
});
}
function drawLines() {
var stroke = new ol.style.Stroke({
color: [255, 0, 0, 1],
width: 6
});
var style = new ol.style.Style({
fill: null,
stroke: stroke,
text: new ol.style.Text({
font: '12px helvetica,sans-serif',
text: "Sandokhan / Wargasm Canal",
fill: new ol.style.Fill({
color: '#000'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
});
var line_feature = new ol.Feature({});
var coords = [
[6607.5, -1921],
[6894, -1921]
];
var layerLines = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.LineString(coords, 'XY'),
name: 'Line',
})]
})
});
layerLines.setStyle(style);
map.addLayer(layerLines);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.8.2/ol.min.css" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.8.2/ol.min.js" type="text/javascript"></script>
<div id="map"></div>
<div id="coord-overlay">[6612, -2252]</div>
<input id="slider" type="range" min="0" max="1" step="0.1" value="1" oninput="layer.setOpacity(this.value)">
You are looking for a resolution listener, the API docs is an excellent place:
map.getView().on('change:resolution', function(){
var zoom = map.getView().getZoom();
// your conditions
if (zoom < 10) {
// your ol.layer.Vector assuming `vector_layer` global variable
vector_layer.setStyle(style_with_another_radius);
}
});
you can listen to the moveend event for the zoom, however it is also fired when you move the map:
map.on('moveend', function(){
var radius= map.getView().getZoom() * someFactor; // or whatever +,/ ...
yourVectorVillage.setStyle(new ol.style.Circle({ radius : radius}));
// or a style of your own where you can modify the radius
});
I was planning to draw polygon from lat long values referring this code.
open layers 3 how to draw a polygon programmically?
var polyCoordinates =[[1.300910900488229, 44.28372648003116],[1.3373031124022878, 44.13311552125895],[1.6648330196289067, 44.12030076099872]];
var polygon = new OpenLayers.Geometry.Polygon([polyCoordinates]);
// Create feature with polygon.
var feature = new OpenLayers.Feature(polygon);
// Create vector source and the feature to it.
var vectorSource = new OpenLayers.source.Vector();
// Create the vectorial layer
var vectorLayer = new OpenLayers.Layer.Vector('Vector Layer', {
source: vectorSource
styleMap: new OpenLayers.StyleMap({
'default': OpenLayers.Util.applyDefaults({
strokeWidth: 3,
graphicName: 'triangle',
pointRadius: '${radius}',
rotation: '${angle}'
}, OpenLayers.Feature.Vector.style['default']
),
'select': OpenLayers.Util.applyDefaults({
pointRadius: '${radius}'
}, OpenLayers.Feature.Vector.style['select']
)
})
});
OpenLayers.source is undefined is showing as error. Any help would be appreciated.
var sitePoints = [];
var coordinates =[{"long":1.300910900488229,"lat":44.28372648003116},
{"long":1.3373031124022878,"lat":44.13311552125895},
{"long":1.6648330196289067,"lat":44.12030076099872}];
var siteStyle = {
label:'ring',
title: 'press to close as a ring',
cursor: "pointer",
fontSize: '8px',
fontColor: '#222',
pointRadius: 10,
fillColor: '#cccccc',
strokeColor: '#444444'
};
var epsg4326 = new OpenLayers.Projection("EPSG:4326");
for (var i in coordinates) {
var coord = coordinates[i];
var point = new OpenLayers.Geometry.Point(coord.long, coord.lat);
// transform from WGS 1984 to Spherical Mercator
point.transform(epsg4326, map.getProjectionObject());
sitePoints.push(point);
}
console.log(sitePoints);
var linearRing = new OpenLayers.Geometry.LinearRing(sitePoints);
var geometry = new OpenLayers.Geometry.Polygon([linearRing]);
var polygonFeature = new OpenLayers.Feature.Vector(geometry, null, siteStyle);
vectorLayer.addFeatures([polygonFeature]);
map.addLayer(vectorLayer);
Here is a proper way to do this in OpenLayers 3, which has a different API than previous versions.
var polyCoordinates =[
[1.300910900488229, 44.28372648003116],
[1.3373031124022878, 44.13311552125895],
[1.6648330196289067, 44.12030076099872]];
var polygon = new ol.geom.Polygon([polyCoordinates]);
polygon.applyTransform(ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
// Create feature with polygon.
var feature = new ol.Feature({
geometry: polygon
});
// Create vector source and the feature to it.
var vectorSource = new ol.source.Vector({
features: [feature]
});
// Create the vectorial layer
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#eedd00',
width: 3
})
})
});
Edit: If you stick with OpenLayers 2, you need to create the polygon via linear ring. The setup is a little bit different. There is no OpenLayers source to deal with.
var polyCoordinates =[
[1.300910900488229, 44.28372648003116],
[1.3373031124022878, 44.13311552125895],
[1.6648330196289067, 44.12030076099872]];
// Create the polygon via linear ring
var points = [];
for (var i = 0; i < polyCoordinates.length; i++) {
coord = polyCoordinates[i];
points.push(new OpenLayers.Geometry.Point(coord[0], coord[1]));
}
var linearRing = new OpenLayers.Geometry.LinearRing(points);
var polygon = new OpenLayers.Geometry.Polygon([linearRing]);
var srcProj = new OpenLayers.Projection("EPSG:4326");
var targetProj = new OpenLayers.Projection("EPSG:3857");
polygon.transform(srcProj, targetProj);
// Create feature with polygon.
var feature = new OpenLayers.Feature.Vector(polygon);
// Create the vectorial layer
var vectorLayer = new OpenLayers.Layer.Vector('Vector Layer',
OpenLayers.Feature.Vector.style['default']
);
vectorLayer.addFeatures([feature]);