MarkerClusters in OpenLayer 6.3.1 with WMS as source - javascript

I am using OpenLayer version 6.3.1 and would like to know how to do a MarkerClusters using WMS data source.
My problem is that I don't know how to link the Cluster with WMS. the WMS source is a point.shp (geometrically)
I tried to replace the cluster sources by the WMS one, but it doesn't work.
Here is my code
var ImageWMS = new ImageWMS({
url: 'http://localhost:8080/geoserver/ACCESSOINSMADA/wms',
params: {'LAYERS': 'ACCESSOINSMADA:csb2-pub', 'TILED': true},
serverType: 'geoserver',
transition: 0,
});
var ImageLayers = new ImageLayer({
source: ImageWMS,
})
var distance = document.getElementById('distance');
var count = 20000;
var features = new Array(count);
var e = 3500000;
for (var i = 0; i < count; ++i) {
var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
features[i] = new Feature(new Point(coordinates));
}
var source = new VectorSource({
features: features,
});
var clusterSource = new Cluster({
distance: parseInt(distance.value, 10),
source: source,
});
var styleCache = {};
var clusters = new VectorLayer({
source: clusterSource,
style: function (feature) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
style = new Style({
image: new CircleStyle({
radius: 10,
stroke: new Stroke({
color: '#fff',
}),
fill: new Fill({
color: '#3399CC',
}),
}),
text: new Text({
text: size.toString(),
fill: new Fill({
color: '#fff',
}),
}),
});
styleCache[size] = style;
}
return style;
},
});

A WMS output is (generally) an image, so you won't be able to change the data and cluster it in a client such as OpenLayers; to do that you'll need to fetch the data through say a WFS.
As an alternative to clustering points in a client, you can configure the WMS to serve out clustered points.
For an example see:
WMS providing clustered points, shown in OpenLayers

Related

Problem with drawing arrows in OpenLayers

I would like to draw the simple arrow in OpenLayers.
I found some examples here:
OpenLayer 4 draw arrows on map
https://openlayers.org/en/latest/examples/line-arrows.html
Draw arrow without using any image in openlayers3
and made some code:
var arrowInteraction = new ol.interaction.Draw({
type: 'LineString',
source: vectorLayer.getSource(),
geometryFunction: function(coordinates, geometry) {
var geometry = coordinates.getGeometry();
var styles = [
// linestring
new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
})
})
];
geometry.forEachSegment(function (start, end) {
var dx = end[0] - start[0];
var dy = end[1] - start[1];
var rotation = Math.atan2(dy, dx);
var lineStr1 = new ol.geom.LineString([end, [end[0] - 200000, end[1]
+ 200000]]);
lineStr1.rotate(rotation, end);
var lineStr2 = new ol.geom.LineString([end, [end[0] - 200000, end[1]
- 200000]]);
lineStr2.rotate(rotation, end);
var stroke = new ol.style.Stroke({
color: 'green',
width: 1
});
styles.push(new ol.style.Style({
geometry: lineStr1,
stroke: stroke
}));
styles.push(new ol.style.Style({
geometry: lineStr2,
stroke: stroke
}));
});
return styles;
}
I am getting an error:
coordinates.getGeometry is not a function
What can be wrong here?
My full code is here:
https://mktest.opx.pl/
This might help: TypeError: Cannot read properties of undefined (reading 'id')
If I understand it right, the functions aren't called synchronized.
In that tutorial, he catch it with:
itemToForm = () => {
if(this.item === undefined) {return}
// The rest of the code
}
But you can also catch it with
if(yourObjectOrValue === undefined) {// The rest of the code}

How to calculate a distance between two points along a path?

I'm using openlayers3 and I have the encoded geometry. I can get the coordinates (lat,lng) for all points in the path (around 500 points per path). Given a random point inside the path, how do I calculate the distance between the beginning of the path up to that point?
I've taken a look at turfjs and it looks very promising, but the solution I pictured using it wouldn't be very nice. Taking a random point (p1), I could discover the point (p2) of the path that is closest to p1, then generate a new polygon and calculate its total distance. It may have performance issues, although the search would be O(log n) and the new polygon O(n).
EDIT: the random point is not necessarily inside the path, it's a GPS coordinate and there's a margin for error.
EDIT 2: estimation on the number of points was off, each path has about 500 points, not 5k
Does anyone know of a better approach? I'm not very experienced with either openlayers3 nor turfjs.
As you mentioned you're using OpenLayers 3, I've done an example using OpenLayers 3, the idea is:
Get Closest Point across the LineString given a coordinate
Iterate over LineString points calculating the distance of each individual paths and see if our closest point intersects the individual path.
/* Let's Generate a Random LineString */
var length = 5000;
var minLongitude = Math.random()*-180 + 180;
var minLatitude = Math.random()*-90 + 90;
var wgs84Sphere = new ol.Sphere(6378137);
var lastPoint = [minLongitude, minLatitude]
var points = Array.from({ length })
.map( _ =>{
var newPoint = [
Math.random() * (Math.random() > 0.8 ? -.005 : .005) + lastPoint[0]
, Math.random() * (Math.random() > 0.2 ? -.005 : .005) + lastPoint[1]
]
lastPoint = newPoint;
return newPoint;
})
var distanceTotal = points
.reduce((dis, p, i)=>{
if(points[i + 1])
dis += wgs84Sphere.haversineDistance(p, points[i + 1] )
return dis;
}, 0);
console.log(distanceTotal)
var extent = new ol.extent.boundingExtent(points)
//console.log(points)
var lineString = new ol.Feature({
geometry : new ol.geom.LineString(points)
});
var source = new ol.source.Vector();
var layer = new ol.layer.Vector({ source });
source.addFeature(lineString);
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
projection : 'EPSG:4326',
center: [0, 0],
zoom: 2
})
});
map.addLayer(layer)
map.getView().fit(extent, map.getSize())
var auxLayer = new ol.layer.Vector({ source : new ol.source.Vector() })
var styleAux = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 2
})
});
var styleAuxLine = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 0.5
})
});
var styleAuxPoint = new ol.style.Style({
image : new ol.style.Circle({
radius: 5,
fill: null,
stroke: new ol.style.Stroke({color: 'black', width: 2})
})
});
var styleAuxSourcePoint = new ol.style.Style({
image : new ol.style.Circle({
radius: 3,
fill: null,
stroke: new ol.style.Stroke({color: '#00bbff', width: 0.5})
})
});
auxLayer.setStyle(function(f, r){
var type = f.getGeometry().getType();
if(type === 'LineString') return styleAux;
return styleAuxPoint;
})
map.addLayer(auxLayer);
map.on('pointermove', function(e){
if(e.dragging) return;
var coord = e.coordinate;
var distance = 0;
var pointsGeometry = [];
var sourcePointFeature = new ol.Feature({
geometry : new ol.geom.Point(coord)
});
var closestPoint = lineString.getGeometry().getClosestPoint(coord);
var lineDiffFeature = new ol.Feature({
geometry : new ol.geom.LineString([
coord, closestPoint
])
});
for(let i = 0; i< points.length - 1; i++){
var p = points[i]
var next = points[i + 1];
var subLineStringGeom = new ol.geom.LineString([ p, next ]);
pointsGeometry.push(p);
var e = 1e-10;
var extent = [ closestPoint[0] - e, closestPoint[1] - e
, closestPoint[0] + e, closestPoint[1] + e
]
if(subLineStringGeom.intersectsExtent(extent)){
//console.log(i);
pointsGeometry.push(closestPoint);
distance += wgs84Sphere.haversineDistance(p, closestPoint);
break;
}
distance += wgs84Sphere.haversineDistance(p, next);
}
console.log(closestPoint)
var cpGeometry = new ol.geom.Point(closestPoint);
var cpFeature = new ol.Feature({ geometry : cpGeometry });
var geometry = new ol.geom.LineString(pointsGeometry);
var newFeature = new ol.Feature({ geometry });
auxLayer.getSource().clear();
auxLayer.getSource().refresh();
auxLayer.getSource().addFeature(lineDiffFeature);
auxLayer.getSource().addFeature(newFeature);
auxLayer.getSource().addFeature(sourcePointFeature);
auxLayer.getSource().addFeature(cpFeature);
sourcePointFeature.setStyle(styleAuxSourcePoint);
lineDiffFeature.setStyle(styleAuxLine);
//console.log(geometry.getLength())
console.log(distance);
})
html, body, #map {
width : 100%;
height : 100%;
padding : 0px;
margin : 0px;
}
<script src="https://openlayers.org/en/v3.20.1/build/ol.js"></script>
<link href="https://openlayers.org/en/v3.20.1/css/ol.css" rel="stylesheet"/>
<div id="map" class="map" tabindex="0"></div>

minimal size for a rectangle in style

I'm writing an application where users can mark regions on a world map. Now these regions can be very small, so that it's hard to click on them when not zoomed in.
Is there a way how I can define (e.g. in the style function) that a (rectangle) feature should always be rendered with at least e.g. 10px × 10px?
Update: some code I currently use:
on the drawing side:
var draw = new ol.interaction.Draw({
source: vectorSource,
type: 'LineString',
geometryFunction: function(coordinates, geometry) {
if(!geometry) {
geometry = new ol.geom.Polygon(null);
}
var start = coordinates[0];
var end = coordinates[1];
geometry.setCoordinates([[
start,
[start[0], end[1]],
end,
[end[0], start[1]],
start
]]);
return geometry;
},
maxPoints: 2
});
draw.on('drawend', function(e) {
var extent = e.feature.getGeometry().getExtent();
extent = app.map.rlonlate(extent); // own function to convert it from map coordinates into lat/lon
// some code to save the extent to the database
});
and on the displaying side:
vectorSource.addFeature(
new ol.Feature({
geometry: ol.geom.Polygon.fromExtent(app.map.lonlate(extent)),
// … some more custom properties like a display name …
})
);
the style function:
function(feature) {
return [new ol.style.Style({
stroke: new ol.style.Stroke({
color: feature.get('mine') ? '#204a87' : '#729fcf',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, ' + (feature.get('mine') ? '0.5' : '0.2') + ')'
})
})];
}
Using a style function is a good idea. The second argument of the style function is resolution which you can use to check if your feature geometry would be smaller than e.g. 10 px at the current resolution:
var styleFn = function(feature, resolution) {
var minSizePx = 30;
var minSize = minSizePx * resolution;
var extent = feature.getGeometry().getExtent();
if (ol.extent.getWidth(extent) < minSize || ol.extent.getHeight(extent) < minSize) {
// special style for polygons that are too small
var center = new ol.geom.Point(ol.extent.getCenter(extent));
return new ol.style.Style({
geometry: center,
image: ...
} else {
// normal style
return defaultStyle;
}
};
http://jsfiddle.net/ukc0nmy2/1/

How to drawing animated openlayers linestring path?

I using openlaers map api. I want to display animated route in my path like http://jerusalem.com/map#!/tour/the_way_of_the_cross/location/abu_jaafar. How to do that? Thank you.
This is my Java Script, I get data from XML file.
<script type="text/javascript">
var zoom=13
var map; //complex object of type OpenLayers.Map
function init() {
map = new OpenLayers.Map ("map", {
controls:[
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.Attribution()],
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
maxResolution: 156543.0399,
numZoomLevels: 19,
units: 'm',
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326")
} );
// Define the map layer
// Here we use a predefined layer that will be kept up to date with URL changes
layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
map.addLayer(layerMapnik);
layerCycleMap = new OpenLayers.Layer.OSM.CycleMap("CycleMap");
map.addLayer(layerCycleMap);
layerMarkers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(layerMarkers);
// Add the Layer with the GPX Track
var lgpx = new OpenLayers.Layer.Vector("Descrizione del layer", {
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: "c.php",
format: new OpenLayers.Format.GPX()
}),
style: {strokeColor: "blue", strokeWidth: 5, strokeOpacity: 0.5},
projection: new OpenLayers.Projection("EPSG:4326")
});
map.addLayer(lgpx);
}
</script>
Try the answer at Drawing animated openlayers linestring path. It seems to be quite similar.
Here is the important part of the answer:
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.

OL3: how to modify selected feature style based on zoom?

I use the following code to modify the radius of a Circle marker based on the zoom level:
//add the layer to the map
map.addLayer(vectorLayer);
//add selection interactivity, using the default OL3 style
var select = new ol.interaction.Select();
map.addInteraction(select);
map.getView().on('change:resolution', function(evt) {
var zoom = map.getView().getZoom();
var radius = zoom / 2 + 1;
var newStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
fill: new ol.style.Fill({color: 'red'}),
stroke: new ol.style.Stroke({color: 'black', width: 1})
})
})
vectorLayer.setStyle(newStyle);
});
But the problem I have is that if I select a feature on the map, the selected/highlighed style does not change when the map zoom changes. How can I also dynamically modify the style of selected features based on zoom/resolution?
Clarification The code above already works for changing radius of all features on the map, but in addition to that I also need the radius of selected features to change. Both selected and unselected features should be changing based on zoom level.
You need to set a style function on interaction constructor like:
var select = new ol.interaction.Select({
style: function(feature, resolution){
var zoom = map.getView().getZoom();
var radius = zoom / 2 + 1;
console.info(radius);
var newStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
fill: new ol.style.Fill({color: 'red'}),
stroke: new ol.style.Stroke({color: 'black', width: 1})
})
});
return [newStyle];
}
});
A working demo.
Use the scale base for the radius resizing when zoomed.
map.getCurrentScale = function () {
//var map = this.getMap();
var map = this;
var view = map.getView();
var resolution = view.getResolution();
var units = map.getView().getProjection().getUnits();
var dpi = 25.4 / 0.28;
var mpu = ol.proj.METERS_PER_UNIT[units];
var scale = resolution * mpu * 39.37 * dpi;
return scale;
};
map.getView().on('change:resolution', function(evt){
var divScale = 60;// to adjusting
var radius = map.getCurrentScale()/divScale;
feature.getStyle().getGeometry().setRadius(radius);
})
Did you set the radius in that other style (selected/highlighed), too?

Categories