OpenLayers 2 - Set fill and opacity to Polygon Style - javascript

My goal is to use for different shapes (Triangle, Circle, Square, Hexagon etc.) different fill colors and opacity values for each shape.
With the below code I can draw the shapes, set different titles and stroke colors. But I'm not able to set the fill color and the opacity values.
I checked the documentation and its looks like I could achieve this with "fillColor" and "fillOpacity" but it doesn't works.
function GetLonLatObj(lat, lon){
var lonLat = new OpenLayers.LonLat( lon ,lat )
.transform(
new OpenLayers.Projection("EPSG:4326"), // Transformation aus dem Koordinatensystem WGS 1984
map.getProjectionObject() // in das Koordinatensystem 'Spherical Mercator Projection'
);
return lonLat
}
var points = []
var fontColor = "blue";
var title = "Test";
var map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
var zoom=16;
latLonPoint = GetLonLatObj("46.76", "7.606944444444444");
latLonPoint2 = GetLonLatObj("46.735", "7.543055555555555");
latLonPoint3 = GetLonLatObj("46.7169444", "7.569166666666667");
latLonPoint4 = GetLonLatObj("46.76", "7.606944444444444");
latPoint = latLonPoint.lat
lonPoint = latLonPoint.lon
latPoint2 = latLonPoint2.lat
lonPoint2 = latLonPoint2.lon
latPoint3 = latLonPoint3.lat
lonPoint3 = latLonPoint3.lon
latPoint4 = latLonPoint4.lat
lonPoint4 = latLonPoint4.lon
//var point = new OpenLayers.Geometry.Point(828260.4259880, 5933577.75538379);
point = new OpenLayers.Geometry.Point(lonPoint, latPoint);
point2 = new OpenLayers.Geometry.Point(lonPoint2, latPoint2);
point3 = new OpenLayers.Geometry.Point(lonPoint3, latPoint3);
point4 = new OpenLayers.Geometry.Point(lonPoint4, latPoint4);
points.push(point);
points.push(point2);
points.push(point3);
points.push(point4);
var selected_polygon_style = {
strokeWidth: "3",
strokeColor: fontColor,
fontColor: "red",
fontSize: "16px",
fontWeight: "bold",
fontColor: "black",
label: title
};
vectorLayer = new OpenLayers.Layer.Vector();
vectorLayer.style = selected_polygon_style;
//map.addLayers([vector]);
vectorLayer.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points))]);
map.addLayers([vectorLayer]);
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(latLonPoint));
map.setCenter (latLonPoint, zoom);
<script src="https://buhli.dyndns.org:444/openlayers.js"></script>
<html>
<body>
<div id="mapdiv"></div>
</body>
</html>
Can someone help me here?
Thank you very much and best regards

The problem was the LineString in the follow command.
vectorLayer.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points))]);
I could fix it with it as I replaced with LinearRing.
A LinearRing is a special LineString which is closed. A LineString can but must not be closed.

Related

Draw circle with EPSG:4326 coordinate center in image layer OpenLayers 2

I'm trying to create a circle with a center like this var center = {lat: 12.972876848034, lng: 77.589721116026} (I pick up this point on Google Maps) in an image layer from an JPG file. But the circle isn't appear.
Here is my code.
<!DOCTYPE html>
<html>
<head>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init() {
var imgWidth = 1864;
var imgHeight = 1070;
var extend = new OpenLayers.Bounds(77.58356602859499, 12.965959702159019, 77.6046633014679, 12.976413580812167);
var layer = new OpenLayers.Layer.Image(
'Image layer',
'images/view.jpg',
extend,
new OpenLayers.Size(imgWidth, imgHeight),
{numZoomLevels: 6}
);
map = new OpenLayers.Map(
{
div: "mapdiv",
maxExtent: extend,
maxResolution: 156543,
numZoomLevels: 6
}
);
map.addLayers([layer]);
map.zoomToMaxExtent();
var center = {lat: 12.972876848034, lng: 77.589721116026}
var lonLat = new OpenLayers.LonLat(center.lng, center.lat)
var pCenter = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
var circle = OpenLayers.Geometry.Polygon.createRegularPolygon(pCenter, 50, 70, 0);
var circleFeature = new OpenLayers.Feature.Vector(circle);
var circleStyle = new OpenLayers.StyleMap({'strokeColor': '#1E88E5', 'strokeWidth': 2});
var circleLayer = new OpenLayers.Layer.Vector("Route Layer", {styleMap: circleStyle});
circleLayer.addFeatures([circleFeature]);
}
init();
</script>
</head>
<body onload="init()">
<div style="height: 100vh" id="mapdiv"></div>
</body>
How is this caused and how can I solve it?
Thanks in advance for any suggestions.
I've found the answer, because I use EPSG:4326 coordinate, the unit of radius must be in degree. I set radius = 0.1 and now it worked.

OpenLayers.source is undefined - Open layers,Open Street map

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]);

How to serialize OpenLayers features?

I've got OpenLayer map. I'm drawing markers (named features) onto this map, but I don't know how to export/serialize these elements.
There isn't probably any function to export.
Here is my code
var map, vectors, controls;
function init(){
map = new OpenLayers.Map('map');
var wms = new OpenLayers.Layer.OSM( "OSM",
"http://a.tile2.opencyclemap.org/transport/${z}/${x}/${y}.png", {layers: 'basic'});
// allow testing of specific renderers via "?renderer=Canvas", etc
var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;
vectors = new OpenLayers.Layer.Vector("Vector Layer", {
renderers: renderer
});
map.addLayers([wms, vectors]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.addControl(new OpenLayers.Control.MousePosition());
controls = {
point: new OpenLayers.Control.DrawFeature(vectors,
OpenLayers.Handler.Point),
line: new OpenLayers.Control.DrawFeature(vectors,
OpenLayers.Handler.Path),
polygon: new OpenLayers.Control.DrawFeature(vectors,
OpenLayers.Handler.Polygon),
drag: new OpenLayers.Control.DragFeature(vectors)
};
console.log(map.addControl(controls['point']));
var control = controls['point'];
control.activate();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(16.6833, 53.7167).transform(fromProjection, toProjection);
map.setCenter(position, 12);
document.getElementById('noneToggle').checked = true;
}
Please for help me
Ok, I found soulution. All elements are storage in vectors object

how to get uper-left and lower-right x y position of screen in openLayers map?

My problem is that when my map is loaded at that time I want to get X and Y cordinates of all four corners of screen as per resolution. My code:
map = new OpenLayers.Map("mapdiv", {
controls: [new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar()
],
numZoomLevels: 10
});
map.addLayer(new OpenLayers.Layer.OSM("OpenCycleMap"));
epsg4326 = new OpenLayers.Projection("EPSG:4326");
epsg900913 = new OpenLayers.Projection("EPSG:900913");
var lonLat = new OpenLayers.LonLat(72.58, 23.03).transform(epsg4326, epsg900913);
console.log(lonLat);
var zoom = 15;
var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
map.events.register("click", map, function (e) {
var lonlat = map.getLonLatFromViewPortPx(e.xy);
alert(lonlat);
});
markers.addMarker(new OpenLayers.Marker(lonLat));
var polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer");
map.addLayer(polygonLayer);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.addControl(new OpenLayers.Control.MousePosition());
map.setCenter(lonLat, zoom);
You should try to post a fiddle when you can. Assuming you're using OpenLayers v2.
If you meant to ask how to get the corners of the viewport, try:
map.getViewport().getClientRects()[0]
If you meant the extent of the map in coordinates:
map.getExtent()

Drawing animated openlayers linestring path

I have seen an impressive mapping example on http://jerusalem.com/map#!/tour/the_way_of_the_cross/location/abu_jaafar, Does anybody how a similar animation on the drawn path of the points can done using openlayers?
The following fiddle shows the linestrings http://jsfiddle.net/pwuVz/58/ but I need is to be able to animate the line string itself so that the string is not directly drawn.
var map = new OpenLayers.Map( 'map', {theme:null,
controls:[new OpenLayers.Control.Navigation()]} );
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0",
{layers: 'basic'} );
map.addLayer(layer);
map.setCenter([3, 49], 5);
var startPt=new OpenLayers.Geometry.Point( 2, 45);
var endPt=new OpenLayers.Geometry.Point(7,55);
//make the line:
var line=new OpenLayers.Geometry.LineString([startPt, endPt]);
//style
var style={strokeColor:"#0500bd", strokeWidth:15, strokeOpacity: 0.5, strokeColor: '#0000ff'};
//make vector
var fea=new OpenLayers.Feature.Vector(line, {}, style);
//make vectorLayer
var vec= new OpenLayers.Layer.Vector();
//add the feature
vec.addFeatures([fea]);
//add to map
map.addLayer(vec);
setTimeout(function() {
var startPt=new OpenLayers.Geometry.Point( 7, 55);
var endPt=new OpenLayers.Geometry.Point(13,52);
//make the line:
var line=new OpenLayers.Geometry.LineString([startPt, endPt]);
//style
var style={strokeColor:"#0500bd", strokeWidth:15, strokeOpacity: 0.5, strokeColor: '#0000ff'};
//make vector
var fea=new OpenLayers.Feature.Vector(line, {}, style);
//make vectorLayer
var vec= new OpenLayers.Layer.Vector();
//add the feature
vec.addFeatures([fea]);
//add to map
map.addLayer(vec);
}, 2000);
You can animate it by drawing only one part of the line at a time. Here is one way you could do it:
function drawAnimatedLine(startPt, endPt, style, steps, time, fn) {
var directionX = (endPt.x - startPt.x) / steps;
var directionY = (endPt.y - startPt.y) / steps;
var i = 0;
var prevLayer;
var ivlDraw = setInterval(function () {
if (i > steps) {
clearInterval(ivlDraw);
if (fn) fn();
return;
}
var newEndPt = new OpenLayers.Geometry.Point(startPt.x + i * directionX, startPt.y + i * directionY);
var line = new OpenLayers.Geometry.LineString([startPt, newEndPt]);
var fea = new OpenLayers.Feature.Vector(line, {}, style);
var vec = new OpenLayers.Layer.Vector();
vec.addFeatures([fea]);
map.addLayer(vec);
if(prevLayer) map.removeLayer(prevLayer);
prevLayer = vec;
i++;
}, time / steps);
}
The time argument specifies how long you want the animation to last (in milliseconds), and the steps specifies how many steps you want to divide the animation into. fn is a callback that will be executed when the animation is complete.
Here is a jsFiddle demo that demonstrates this.

Categories

Resources