How to slow down mouse before modifyend with OpenLayers - javascript

I have a map with a draggable marker (ol.style.icon in fact).
There is a strange issue:
If I try to move marker, it is like trying to reel in a marlin but after a zoomin/out or a first drag (clic tight then clic release), marker naturally slows down.
I tried to play with PixelTolerance but any difference.
Why and how to immediately slow down this marker, please?
var mark_style = new ol.style.Style({
image: new ol.style.Icon({
anchor: [.5, 48],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: mark_path
})
});
var iconFeature = new ol.Feature(position);
iconFeature.set('style', mark_style);
var vectorLayer = new ol.layer.Vector({
style: function(feature) {
return feature.get('style');
},
source: new ol.source.Vector({features: [iconFeature]})
})
var dragInteraction = new ol.interaction.Modify({
features: new ol.Collection([iconFeature]),
style: null,
pixelTolerance: 10//?
});
dragInteraction.on('modifyend',function(f){
var coordf = f.features.getArray()[0].getGeometry().getCoordinates();
ol.View-view.setCenter(coordf);
GMapWidget.prototype.A = coordf;
GMapWidget.prototype.updatePosition(position);
},iconFeature);
map.addInteraction(dragInteraction);
After a lot of tries, it seems it's a 'modifyend' problem: mouse is fast before first dragInteraction end. How to do please? with a modifystart, no more speed up but then, how to access all mouse positions after first clic ?

well, seems ok with dragInteraction.on(['modifyend', 'modifystart']
I'm a beginner and I don't know why my code is now ok. I succeeded after lot of tries.

Related

Using a style on clustered vectors and unclustered vectors

At the moment Im making a viewer with openlayers, js, css and html.
In my map I have a GeoJSON served by geoserver with a few points that are close to each other. For these points I have made my own SVG's and turned them to icon/png's to be served on the map.
Due to the symbology being connected to a variable: "category" varying from 1 to 3. For this I made a function which I call upon in the "style" parameter at my GEOJSON.
Due to the points being to close to each other I decided to make clusters of them depended on zoomlevel. This all functioned properly however I could not get the same style function to respond on my new clustered layer. After trying several things (mostly changing the function for the style (see below)) I finally made it that the clusters now appear as icon/png's, but the problem is that it does not respond of the "else if" statements in my function anymore and therefor the varying icon's on the "Category" variable are not visible anymore.
Below my code:
/* style icons */
var ottergroen = new ol.style.Icon({
src: 'img/bottlenecks_icons/otter_groen.png',
anchorOrigin: 'bottom-Left',
anchorXUnits: 'fraction',
anchor: [0.1, 0],
imgsize: [2, 2]
});
var ottergeel = new ol.style.Icon({
src: 'img/bottlenecks_icons/otter_geel.png',
anchorOrigin: 'bottom-Left',
anchorXUnits: 'fraction',
anchor: [0.1, 0],
imgsize: [2, 2]
});
var otteroranje = new ol.style.Icon({
src: 'img/bottlenecks_icons/otter_oranje.png',
anchorOrigin: 'bottom-Left',
anchorXUnits: 'fraction',
anchor: [0.1, 0],
});
var otterrood = new ol.style.Icon({
src: 'img/bottlenecks_icons/otter_rood.png',
anchorOrigin: 'bottom-Left',
anchorXUnits: 'fraction',
anchor: [0.1, 0],
});
/*function to call upon the variables and return the right icon */
function getpriority(Category) {
if (Array)
return ottergroen;
else if(Category == "1") {
return otterrood;
} else if (Category == "2"){
return ottergeel;
} else if (Category == "3") {
return ottergroen;
}
};
/* making the clustered layer */
var bottlenecksjsonsource = new ol.source.Vector({
url: 'http://localhost:8080/geoserver/Gbra/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=Gbra%3ABottlenecks_gbra_filtered&outputFormat=application%2Fjson',
format: new ol.format.GeoJSON()
});
var bottlenecksjsonlayer = new ol.layer.Vector({
source: bottlenecksjsonsource
});
// a clustered source is configured with another vector source that it
// operates on
var jsoncluster = new ol.source.Cluster({
source: bottlenecksjsonsource
});
// it needs a layer too
var clusteredbottlenecks = new ol.layer.Vector({
source: jsoncluster,
title: 'bottlenecksclustered',
style: function(feature){
return new ol.style.Style({
image: getpriority(feature.get('Category'))
})
}
});
clusteredbottlenecks.setVisible(false);
map.addLayer(clusteredbottlenecks);
console.log(clusteredbottlenecks);
It would be awesome if someone could tell me what I'M doing wrong here. At the moment it only visualizes this symbol ("ottergroen") as seen in the pictures below on every zoom level:
and below the image of what the non clustered vectors should look like:
Thanks in advance <3!
You have to get the feature inside the cluster. If you have only one it's a feature otherwise it's a cluster.
function getStyle (feature, resolution) {
var features = feature.get('features');
var size = features.length;
// Feature style
if (size===1) {
var cat = features[0].get('category');
// get style
var style = ...
return style;
} else {
// ClusterStyle
return clusterStyle;
}
See example: https://viglino.github.io/ol-ext/examples/map/map.clustering.html

OpenLayers - On click marker zoom at certain zoom level

I want to create on click event on the marker which zooms at a specific level upon click. current code loads marker and upon click zooms to the maximum zoom level of marker. I want to add a specific zoom level in code so when click event happens on the marker it should set view at that zoom level .i have raster tiles on the map at zoom level 16 and above so, when I click on the marker it should zoom to raster tiles and hide marker from there.
var marker = new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: "data.js"
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
scale:0.03,
src: "img.png"
})
})
});
map.addLayer(marker);
map.on("singleclick", (event) => {
const feature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
return feature;
});
if (feature instanceof ol.Feature) {
map.getView().fit(feature.getGeometry());
}
});
Instead of using fit set the view's center and zoom
map.getView().setCenter(ol.extent.getCenter(feature.getGeometry().getExtent()));
map.getView().setZoom(16);
You can "hide" a feature by giving it a null style
feature.setStyle(null);

Openlayers Hover render order, hover feature rendering over all other features

I'm looking for a way to render a hover feature vector only over that feature, to essentially render the hover vector over its feature without rendering over other features (specifically, LineString hovers not rendering over proximate markers)
I have hovering set up without issue as per the vector example, the features all rendering in the order I would like (LineStrings are below markers). The issue is that when a LineString is hovered over its hover feature is rendered not only over that LineString but also any marker that the LineString crosses under, and so there is a big streak of the LineString's hover over that marker. I can see how this makes sense just considering how the feature-overlaying vector works, but I can't see how to adjust it as I would like.
I've found several posts that seem to offer incongruous advice on setting a zIndex in the styles or using a renderOrder function, though none have seemed exactly applicable to this situation, or are beyond my n00b capacities. I have tried setting a zIndex on all concerned Styles as well as something along the lines of this renderOrder function, but not to the desired effect. Specifically with the latter, I couldn't figure out where to put the function so that the hover might render according to it.
Any advice is greatly appreciated!
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([132.4903, 34.0024]),
zoom: 4
})
});
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: '../static/gpx/summer3.kml',
format: new ol.format.KML({
extractStyles: false
})
}),
style: function(feature) {
return routeStyle;
},
});
vectorLayer.getSource().on('addfeature', function(event) {
event.feature.set('hoverstyle', 'route');
});
map.addLayer(vectorLayer);
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: '../static/gpx/testmoo3.kml',
format: new ol.format.KML({
extractStyles: false,
}),
}),
style: function(feature) {
return iconStyle;
},
});
vectorLayer.getSource().on('addfeature', function(event) {
event.feature.set('hoverstyle', 'route');
});
map.addLayer(vectorLayer);
var hoverStyles = {
'moo': new ol.style.Icon({
anchor: [0.5, 30],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: '../static/GPX/icon/mooinb.png',
}),
'route': new ol.style.Stroke({
color: 'rgba(236, 26, 201, 0.5)',
width: 5
})
};
var routeStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(209,14,14,.6)',
width: 4
})
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 30],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: '../static/GPX/icon/moo7.png',
}),
});
var hoverStyleCache = {}
function hoverStyler(feature, resolution) {
var hover = feature.get('hoverstyle');
var geometry = feature.getGeometry().getType();
console.log(hover);
while (geometry === 'Point') {
if (!hoverStyleCache[hover]) {
hoverStyleCache[hover] = new ol.style.Style({
image: hoverStyles[hover],
})
}
return [hoverStyleCache[hover]];
}
while (geometry === 'LineString') {
if (!hoverStyleCache[hover]) {
hoverStyleCache[hover] = new ol.style.Style({
stroke: hoverStyles[hover]
})
}
return [hoverStyleCache[hover]];
}
}
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector(),
map: map,
style: hoverStyler
});
var highlight;
var hover = function(pixel) {
var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature;
});
if (feature !== highlight) {
if (highlight) {
featureOverlay.getSource().removeFeature(highlight);
}
if (feature) {
featureOverlay.getSource().addFeature(feature);
}
highlight = feature;
}
};
map.on('pointermove', function(evt) {
if (evt.dragging) {
return;
}
var pixel = map.getEventPixel(evt.originalEvent);
hover(pixel);
});
***** EDIT 1 *****
Here is a plunkr that at least illustrates what I mean (with the hover vector overlapping the marker).
I continued fiddling around and did get manage to achieve what I wanted, by separating the point and linestring 'featureOverlay' vector into two separate vectors, though to get that to work I also then had to duplicate everything that it implies (the hoverStyler function, the hover feature, etc).
As well, when I referred above to incongruous advice that came especially to the fore as I was able to set the zIndex on that any vector layer, but not in the Styles as I read in just about every other question I found but to the vector itself. Thus,
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector(),
map: map,
style: hoverStyler,
zIndex: 1,
});
worked (with zIndex similarly applied to ever other vector layer), but because points and linestrings share the feature Overlay that also meant that the marker's hover vector image was below the marker it was meant to hover over: applied in this way both linestring and markers or neither hover above.
I thus tried to come up with a function similar to the hoverStyler that differentiates them:
function zIndexer(feature, resolution) {
var geometry = feature.getGeometry().getType();
if (geometry === 'Point') {
return 5
}
if (geometry === 'LineString') {
return 1
}
}
but to no avail (I was unsure what exactly should be returned and tried various inputs; this as others did not work).
So I could settle for duplicated featureOverlay apparatuses, but a handy zIndex function would be of course be preferable :)
(*note: I could not get the zIndex to work in the plunkr as described above, in or out of Styles, hence it does not illustrate my later fiddling but only the original question)
***** EDIT 2 *****
I noted in a comment below on the provided answer that, while the answer works wonderfully, it did make cluster styles styled by function (not mentioned in the original post0 not work. I overcame this with the following vector, which worked but that I am not qualified to say worked well:
var clusterCache = {}
var CLM = new ol.layer.Vector({
source: new ol.source.Vector(),
style: function(feature) {
var size = feature.get('features').length;
var style = clusterCache[size]
if (size === 1) {
return [hoverStyles['moo']]
}
else if (size > 1) {
if (!style) {
style = new ol.style.Style({
image:new ol.style.Icon({
anchor: [0.5, 30],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: '../static/GPX/icon/moo3Hover.png',
}),
text: new ol.style.Text({
text: size.toString(),
font: '12px Calibri,sans-serif',
fill: new ol.style.Fill({
color: '#fff'
}),
stroke: new ol.style.Stroke({
color: '#000',
width: 5
}),
offsetX: 22,
offsetY: 6,
})
}),
clusterCache[size] = style;
}
return style;
}
}
});
hoverLayers['clustermoo'] = CLM;
Approach
The basic idea is you need separate hover layers for the route and the icons (top to bottom):
Icon hover layer
Icon layer
Route hover layer
Route layer
This will mean that say an unhovered icon will draw over the top of a hovered route.
ZIndex
You can't use the style zIndex as it applies only to features within a layer. That is, the layer zIndex has a higher precedence than the style zIndex. In your plunkr I couldn't get the layer zIndex to work at all, but it is implicit in the order the layers are added.
So, you need to:
create separate hover layers
setup the layers in the order I gave above
when hovering a feature, move it to the appropriate hover layer
when unhovering a feature, remove it from the appropriate hover layer
Style Cache
Another thing, your style cache implementation was rather dubious. In fact you do not need a style cache as your are using layer styles and they are only assigned/created once.
Plunkr
Here is an updated plunkr with the above changes: https://plnkr.co/edit/gpswRq3tjTTy9O0L
var createHoverLayer = function(style) {
return new ol.layer.Vector({
source: new ol.source.Vector(),
style: style,
});
}
var hoverLayers = {};
hoverLayers['route'] = createHoverLayer([hoverStyles['route']]);
hoverLayers['moo'] = createHoverLayer([hoverStyles['moo']]);
map.addLayer(routeLayer);
map.addLayer(hoverLayers['route']);
map.addLayer(mooLayer);
map.addLayer(hoverLayers['moo']);
var highlight;
var hover = function(pixel) {
var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature;
});
if (feature !== highlight) {
if (highlight) {
var highlightType = highlight.get('type');
hoverLayers[highlightType].getSource().removeFeature(highlight);
}
if (feature) {
var featureType = feature.get('type');
hoverLayers[featureType].getSource().addFeature(feature);
}
highlight = feature;
}
};
Alternative Approach
do not use separate hover layers at all
use per feature styling via style function
when the feature is hovered/unhovered, set a 'hovered' property on it
to true/false
in the style function, check this property and use the appropriate
style
you will need a style cache with this method

Openlayers3 markers are not showing up on os map

While ago I had help over so about setting up a project where I need to mark random building in NYC and display some info about the building, long story short, I have displayed a openstreetmap using openlayers3, view is fix to Astoria(Queens, NYC).
Now popup is working but markers are not displaying.
I have tried to experiment and change geometry from this
geometry: new ol.geom.Point(ol.proj.fromLonLat([-73.927870, 40.763633]))
to this ol.geom.Point(ol.proj.transform([-73.920935,40.780229], 'EPSG:4326', 'EPSG:3857')),
and use transform instead fromLonLat, but that didn't displayed them, next thing was src in styleIcon, I have download the standard openlayers3 marker and tried to add it from the image folder like src: 'img/icon.png', but that didn't work to.
Can someone please help me understand what is going on, why are mine markers not displaying properly on the map?
This is the JSFiddle for this project, you will see the popup working but no markers.
This JSFiddle is updated and it is working now, markers are displaying properly.
/* Create the map */
// Elements that make up the popup
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
// Add a click handler to hide the popup.
// #return {boolean}.
closer.onclick = function() {
overlay.setPosition(undefined);
closer.blur();
return false;
};
// Create an overlay to anchor the popup
// to the map
var overlay = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
// setting up coordinates for map to display
var city = ol.proj.transform([-73.920935,40.780229], 'EPSG:4326', 'EPSG:3857');
// setting up openlayer3 view
var view = new ol.View({
center: city,
zoom: 15
});
// Create the map
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
crossOrigin: 'anonymous'
})
})
],
overlays: [overlay],
target: 'map',
view: view
});
// Setup markers
var markers = new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-73.927870, 40.763633])),
name: 'Crescent St',
description: 'Apartment'
}),
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-73.917356, 40.763958])),
name: 'Long Island City',
desctiption: 'Apartment'
})
]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixel',
opacity: 0.75,
src: 'https://openlayers.org/en/v3.12.1/examples/data/icon.png',
})
})
});
map.addLayer(markers);
// Setting up click handler for the map
// to render the popup
map.on('singleclick', function(evt) {
var name = map.forEachFeatureAtPixel(evt.pixel, function(feature) {
return feature.get('name');
})
var coordinate = evt.coordinate;
content.innerHTML = name;
overlay.setPosition(coordinate);
});
map.on('pointermove', function(evt) {
map.getTargetElement().style.cursor = map.hasFeatureAtPixel(evt.pixel) ? 'pointer' : '';
});
just remove the https from your src style.
Instead of src: 'https://openlayers.org/en/v3.12.1/examples/data/icon.png',
putsrc: 'http://openlayers.org/en/v3.12.1/examples/data/icon.png',
You also need to zoom out a bit to see your marks

Plot icon on map, based on user's input in Openlayers 3

We upgrading our app with the recent Openlayers 3 maps. And it seems OL 3 use completely different approach in comparisons what they've used in OL 2. Not very good in JS.
We want that user be able to input coordinates (lon, lat) into text fields, press the button and the icon appear on the map. And vice versa - when user click (single click) on the map, these coordinates (lon, lat) should popup on these text fields, to be able save and update it into the DB in the future.
So far I was able to display the map, icon appear on user's click, and completely stuck on how to get coordinates and display them into the text fields. And can't figure out how to make user type in coordinates and get the icon on that location. Here is my code so far:
html
<div id="map" tabindex="0"></div>
<div id="txt">Click to add a marker!</div>
<form>Lon:<input type="text" id="lon" name="lon">
<br>Lat:<input type="text" id="lat" name="lat">
<input type="button" id="get" onlclick = "getLocation" value="plot icon"></form>
And here is JS:
var vectorSource = new ol.source.Vector(),
vectorLayer = new ol.layer.Vector({
source: vectorSource
}),
olview = new ol.View({
center: [0, 0],
zoom: 4,
minZoom: 2,
maxZoom: 20
}),
map = new ol.Map({
target: document.getElementById('map'),
view: olview,
layers: [
new ol.layer.Tile({
style: 'Aerial',
source: new ol.source.MapQuest({ layer: 'osm' })
}),
vectorLayer
]
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: '//openlayers.org/en/v3.8.2/examples/data/icon.png'
}),
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
fill: new ol.style.Fill({ color: '#000' }),
stroke: new ol.style.Stroke({
color: '#fff', width: 2
}),
text: 'lon and lat'
})
});
map.on('click', function(evt){
var feature = new ol.Feature(
new ol.geom.Point(evt.coordinate)
);
feature.setStyle(iconStyle);
vectorSource.clear();
vectorSource.addFeature(feature);
getLocation();
});
function getLocation() {
alert('how to get lon and lat ?!?'); }
You can get the coordinates from a click by calling
evt.coordinate
or
map.getEventCoordinate(evt.originalEvent);
So in your case it would look like:
map.on('click', function(evt) {
var coordinate1 = evt.coordinate;
var coordinate2 = map.getEventCoordinate(evt.originalEvent);
getLocation(coordinate1);
getLocation(coordinate2);
});
function getLocation(coordinate) {
alert(coordinate);
}
To add a marker to a certain point you can follow this example:
how to add markers with OpenLayers 3
(jsfiddle)
Where
ol.geom.Point(ol.proj.transform([Math.random()*360-180, Math.random()*180-90], 'EPSG:4326', 'EPSG:3857')),
would be your desired coordinates e.g.
ol.geom.Point(ol.proj.transform([0.5, 46], 'EPSG:4326', 'EPSG:3857')),
map.on('click', function (evt) {
var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:4326', 'EPSG:3857');
var lon = lonlat[0];
var lat = lonlat[1];}
for getting long and lat you can change EPSG according to your need

Categories

Resources