OpenLayers Remove Layer from map - javascript

I'm using a OpenLayers to add dots on the map from a search result. I can add them just fine, but I want to clear/remove the layer when the user does another search. I've tried using RemoveFeature(), using Destroy(), etc but everything I tried doesn't work.
What am I doing wrong?
http://jsfiddle.net/9Lzc1uu2/6/
var USGSimagery = new ol.layer.Tile({
myattribute: 'USGSimagery',
source: new ol.source.TileWMS(({
url: 'http://raster.nationalmap.gov/arcgis/services/Orthoimagery/USGS_EROS_Ortho_SCALE/ImageServer/WMSServer',
params: {
'LAYERS': 0
}
}))
});
var view = new ol.View({
//projection:projection
center: ol.proj.transform(
[-12934933.3971171, 5405304.89115131], 'EPSG:3857', 'EPSG:3857'),
zoom: 18
})
var geolocStyle = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 1,
src: 'images/icon.png'
}))
});
var map = new ol.Map({
layers: [USGSimagery],
loadTilesWhileInteracting: true,
target: document.getElementById('map'),
view: view
});
var searchResultsStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
});
var TestSearchResults = [{ 'Name': "R0045000030", 'X': "-12934933.3971171", 'Y': "5405304.89115131" },
{ 'Name': "R0238000050", 'X': "-12934887.0227854", 'Y': "5405285.39954225" },
{ 'Name': "R0310260660", 'X': "-12934830.2731638", 'Y': "5405249.69762986" }];
var SearchDots = [];
for (var i = 0; i < TestSearchResults.length; i++)
{
var item = TestSearchResults[i];
var positionFeature = new ol.Feature({
geometry: new ol.geom.Point([item["X"], item["Y"]]),
name: item['Name']
});
positionFeature.setStyle(searchResultsStyle);
SearchDots.push(positionFeature);
}
var featuresSearchResults = new ol.layer.Vector({
map: map,
source: new ol.source.Vector({
features: SearchDots
})
});
function DeleteResults()
{
// Delete Search Vectors from Map
featuresSearchResults.destroy();
}

The appropriate way to destroy features of a layer in OpenLayers 3 is to get the layer source, then clear the source:
function DeleteResults()
{
// Delete Search Vectors from Map
featuresSearchResults.getSource().clear();
};
Api Reference

Related

Map Size not updating on map.updateSize()

I am Using Open layers to publish a Map. But I can't figure out the way to Make the map size dynamic according to Screen Size. As the map remains same on every screen irrespective of the screen size. I also tried map.updatesize(). But that is not working too.
My Code is
layer = new ol.layer.Tile({
title: 'Basemap',
baseLayer: true,
visible: true,
source: new ol.source.TileWMS({
url: 'http://mlinfomaps.in/geoserver/wms',
params: { 'LAYERS': 'MSSDS_WS:MSSDS_BASEMAP', 'TILED': true },
serverType: 'geoserver',
// Countries have transparency, so do not fade tiles:
transition: 0,
crossOrigin: "anonymous"
})
});
var mousePositionControl = new ol.control.MousePosition({
coordinateFormat: ol.coordinate.createStringXY(4),
projection: 'EPSG:4326',
// comment the following two lines to have the mouse position
// be placed within the map.
//className: 'custom-mouse-position',
target: document.getElementById('mouse-position'),
//undefinedHTML: ' '
});
var projection = new ol.proj.Projection({
//code: 'EPSG: 4326', // *code says: 5261 ...try to see if this is right
//extent: [71.6142, 22.3645, 81.8754, 15.1508],
extent:[7970828.0670139585, 1681517.1260521673, 9127778.927138386, 2541280.8202038296]
})
function scaleControl() {
control = new ol.control.ScaleLine({
units: 'metric',
bar: true,
steps: 4,
text: true,
minWidth: 100
});
return control;
}
var sourceMeasure = new ol.source.Vector({
crossOrigin: "anonymous",
});
var vectorMeasure = new ol.layer.Vector({
source: sourceMeasure,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#df1c29',
width: 2
}),
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#df1c29'
})
})
}),
title: 'Measure Overlay',
});
// The Map
//var overlay = new ol.Overlay
// ({
// element: container,
// autoPan: true,
// autoPanAnimation: {
// duration: 250
// }
// });
var view = new ol.View
({
center: ol.proj.transform([76.7997, 18.6298], 'EPSG:4326','EPSG:3857'),
zoom: 7,
extent: projection.getExtent(),
//minZoom:7,
maxZoom: 12
});
var map = new ol.Map
({
target: 'map',
controls: ol.control.defaults().extend([mousePositionControl, scaleControl()]),
view: view,
//fit: view.fit(),
//overlays: [overlay],
layers: [layer]
});
const extent = projection.getExtent()
map.getView().fit(extent);
map.updateSize();
window.onresize = function()
{
setTimeout( function() { map.updateSize();}, 200);
}
'''
The map on different screen looks like this:
On my screen It looks like
https://i.stack.imgur.com/KIYio.png
On my colleague's screen it looks like
https://i.stack.imgur.com/6c4zk.png
Please Help me get through this.
Thanks In Advance!
hello i have the same problem and I solove it by doing that
ts:
html :

Openlayers Set property to KML vector layer markers?

I'm quite new to all of this and am sorry if this is painfully obvious, but I looked around for a solution as best I could and so nevertheless:
I am loading various KML files into a map, including ones of markers, none of which cause problems. I would like to have these markers change when the cursor hovers over them, which I was able to figure out as done by adapting these examples.
However, both use just one style, while I would like different styles for different KML layers. I tried defining and then calling the different styles that I would like to use as per this question.
But I wasn't returned the style that my parameters defined. n00b that I am it took me a while to trial and error what was going on, but console logging in my 'hoverStyler' function (where the styles would be chosen) my style parameter was being returned 'undefined', no matter where I tried defining it. Knowing that, I went into the KML itself and added extended data of my parameter ('hoverstyle'), and the function then worked for whatever marker (or route) I added that to.
The issue that I would like resolved is that it is a bit cumbersome to have to go into the KML and define this for every marker, and I assume that same as they're all loaded together that there must be a way to assign them all this property together, too.
I just have no idea what that is. Any advise is greatly appreciated!
Code:
(there is a certain deliberate redundancy in styles to better give me feedback as to what was and wasn't working)
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;
},
});
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;
},
});
map.addLayer(vectorLayer);
var hoverStyles = {
'moo': new ol.style.Icon({
anchor: [0.5, 30],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: '../static/GPX/icon/mooinb.png',
}),
'moo2': new ol.style.Icon({
anchor: [0.5, 30],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: '../static/GPX/icon/moo2.png'
}),
'route1': 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 defaultRouteStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(130,188,35,.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 defaultIconStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 30],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: '../static/GPX/icon/moo.png'
}),
});
var hoverStyleCache = {}
function hoverStyler(feature, resolution) {
var hover = feature.get('hoverstyle');
var geometry = feature.getGeometry().getType();
console.log(hover);
while (geometry === 'Point') {
if (!hover || !hoverStyles[hover]) {
return [defaultIconStyle];
}
if (!hoverStyleCache[hover]) {
hoverStyleCache[hover] = new ol.style.Style({
image:hoverStyles[hover],
})
}
return [hoverStyleCache[hover]];
}
while (geometry === 'LineString') {
if (!hover || !hoverStyles[hover]) {
return [defaultRouteStyle];
}
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;
}
};
You can set properties as the features are loaded
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', 'moo');
});
map.addLayer(vectorLayer);

rendering opensensemap IDW features via openlayers

I'm trying to render some extra features on map using openlayers. The features can be fetched from the opensensemap API, but for some reason they are not rendered. As I am completely new to openlayers, and dont know much javascript either, I hope for some help.
live code: https://ttnkn.github.io/map/pax/
var GeoStyle = {
'Point': new ol.style.Style({
image: new ol.style.Icon({
src: '../img/bike.png',
scale: 0.075,
})
}),
'Circle': new ol.style.Circle({
fill: new ol.style.Fill({
color: 'rgba(255,255,255,0.4)'
}),
stroke: ol.style.Stroke({
color: '#3399CC',
width: 1.25
}),
radius: 5
})
};
function GeoStyleFunc (feature,resolution) {
return GeoStyle[feature.getGeometry().getType()];
}
var VectorSource = new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: 'https://api.opensensemap.org/boxes?bbox=9.118815,47.653129,9.228427,47.698786&format=geojson&exposure=mobile',
});
var VectorTile = new ol.source.XYZ({
url: 'http://tile.memomaps.de/tilegen/{z}/{x}/{y}.png ',
attributions: 'Map © OSM | Tiles © MeMoMaps | Data © OpenSenseMap'
});
var map = new ol.Map({
target: document.getElementById('map'),
layers: [
new ol.layer.Tile({
source: VectorTile
}),
new ol.layer.Vector({
source: VectorSource,
style: GeoStyleFunc
})
],
controls: ol.control.defaults({ zoom: true, attribution: true }),
view: new ol.View({
center: ol.proj.fromLonLat([9.173, 47.672]),
zoom: 15,
maxZoom: 17,
minZoom: 13
})
});
var url = 'https://api.opensensemap.org/statistics/idw?bbox=9.118815,47.653129,9.228427,47.698786&phenomenon=Temperatur&gridType=hex&cellWidth=2';
fetch(url).then(value => {
value.json().then(value => {
var featureJson = value.data.featureCollection;
var features = (new ol.format.GeoJSON()).readFeatures(featureJson);
var vectorSourceHEX = new ol.source.Vector({
features: features,
projection: ol.proj.get('EPSG:4326')
});
var vectorLayer = new ol.layer.Vector({
source: vectorSourceHEX,
// style: GeoStyleFunc
});
map.addLayer(vectorLayer);
});
}, error => { console.log(error) });
The projection option isn't used in vector sources. If you use readFeatures you must transform the data to the view projection (when you construct a source with a url that is done automatically).
var features = (new ol.format.GeoJSON()).readFeatures(featureJson, {
dataProjection: 'EPSG:4326',
featureProjection: map.getView().getProjection()
});
var vectorSource = new ol.source.Vector({
features: features,
});

LineString direction arrows in Openlayers 4

I'm trying to make a LineString which has arrows in the end of each line to show direction of the route. I use an example from the official site: https://openlayers.org/en/latest/examples/line-arrows.html
The example code creates arrows by user's drawing, but I need arrows for given LineString.
My code contains icons for end and finish of the route.
When I use
'route': new ol.style.Style({
stroke: new ol.style.Stroke({
width: 6, color: [23, 120, 22, 0.6]
})
}),
in styles, my code works. But when I put style for Linestring from the example, it gives me an error saying "Uncaught TypeError: c.Y is not a function".
Here is my code:
var points = [
[76.8412, 43.2245], [76.8405, 43.2210], [76.8479, 43.2200], [76.8512, 43.2220]
];
var route = new ol.geom.LineString(points);
route.transform('EPSG:4326', 'EPSG:3857');
var routeFeature = new ol.Feature({
type: 'route',
geometry: route
});
var startMarker = new ol.Feature({
type: 'icon-a',
geometry: new ol.geom.Point(ol.proj.fromLonLat(points[0]))
});
var endMarker = new ol.Feature({
type: 'icon-b',
geometry: new ol.geom.Point(ol.proj.fromLonLat(points[points.length - 1]))
});
var styles = {
'route': function(feature) {
var geometry = feature.getGeometry();
var styles = [
// linestring
new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'img/icon-a.png'
})
})
];
geometry.forEachSegment(function(start, end) {
var dx = end[0] - start[0];
var dy = end[1] - start[1];
var rotation = Math.atan2(dy, dx);
// arrows
styles.push(new ol.style.Style({
geometry: new ol.geom.Point(end),
image: new ol.style.Icon({
src: 'https://openlayers.org/en/v4.6.3/examples/data/arrow.png',
anchor: [0.75, 0.5],
rotateWithView: true,
rotation: -rotation
})
}));
});
return styles;
},
'icon-a': new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'img/icon-a.png'
})
}),
'icon-b': new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'img/icon-b.png'
})
})
};
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [routeFeature, startMarker, endMarker]
}),
style: function(feature) {
return styles[feature.get('type')];
}
});
var center = ol.proj.fromLonLat([76.8512, 43.2220]);
var map = new ol.Map({
target: document.getElementById('map'),
view: new ol.View({
center: center,
zoom: 15,
minZoom: 2,
maxZoom: 19
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
]
});
#map {
/* just for testing purposes */
width: 100%;
min-width: 100px;
max-width: 500px;
margin-top: 50px;
height: 50px;
}
<link href="https://openlayers.org/en/v4.6.4/css/ol.css" rel="stylesheet"/>
<script src="https://openlayers.org/en/v4.6.4/build/ol-debug.js"></script>
<div id="map"></div>
Firstly, you can use ol-debug.js instead of ol.js, which is uncompressed and helps debugging. The exception you get is
TypeError: style.getImage is not a function (Line 30443)
You get that error because your styles object is mixed: some styles are functions, some are plain Style objects.
You might think that OL can handle both, and you are normally right. However, you provide a function to vectorLayer, so OL detects that you provided a function and calls it. The return value of that function is expected to be a style object. But for route, that returns a function instead!
So when OL calls
style: function(feature) {
return styles[feature.get('type')];
}
It gets styles for the types icon-a, icon-b, but an function for route.
You need to enhance your style function to handle that special case:
style: function(feature) {
const myStyle = stylesMap[feature.get('type')];
if (myStyle instanceof Function) {
return myStyle(feature);
}
return myStyle;
}
PS: Using the same name for a variable twice (styles) is bad practice and can lead to weird bugs.
Here is the runnable example:
var points = [
[76.8412, 43.2245],
[76.8405, 43.2210],
[76.8479, 43.2200],
[76.8512, 43.2220]
];
var route = new ol.geom.LineString(points);
route.transform('EPSG:4326', 'EPSG:3857');
var routeFeature = new ol.Feature({
type: 'route',
geometry: route
});
var startMarker = new ol.Feature({
type: 'icon-a',
geometry: new ol.geom.Point(ol.proj.fromLonLat(points[0]))
});
var endMarker = new ol.Feature({
type: 'icon-b',
geometry: new ol.geom.Point(ol.proj.fromLonLat(points[points.length - 1]))
});
var stylesMap = {
'route': function(feature) {
var geometry = feature.getGeometry();
var styles = [
// linestring
new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'img/icon-a.png'
})
})
];
geometry.forEachSegment(function(start, end) {
var dx = end[0] - start[0];
var dy = end[1] - start[1];
var rotation = Math.atan2(dy, dx);
// arrows
styles.push(new ol.style.Style({
geometry: new ol.geom.Point(end),
image: new ol.style.Icon({
src: 'https://openlayers.org/en/v4.6.5/examples/data/arrow.png',
anchor: [0.75, 0.5],
rotateWithView: true,
rotation: -rotation
})
}));
});
return styles;
},
'icon-a': new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'img/icon-a.png'
})
}),
'icon-b': new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'img/icon-b.png'
})
})
};
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [routeFeature, startMarker, endMarker]
}),
style: function(feature) {
const myStyle = stylesMap[feature.get('type')];
if (myStyle instanceof Function) {
return myStyle(feature);
}
return myStyle;
}
});
var center = ol.proj.fromLonLat([76.8512, 43.2220]);
var map = new ol.Map({
target: document.getElementById('map'),
view: new ol.View({
center: center,
zoom: 15,
minZoom: 2,
maxZoom: 19
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
]
});
html,
body {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
#map {
/* just for testing purposes */
width: 100%;
height: 100%;
}
<link href="https://openlayers.org/en/v4.6.5/css/ol.css" rel="stylesheet" />
<script src="https://openlayers.org/en/v4.6.5/build/ol-debug.js"></script>
<div id="map"></div>

openlayers markers with popup

I am trying to display a map with markers. I want the ability to click these markers such that extra information can be displayed (similiar to the way it works in google earth). I have the map and the markers (or features) but can not get the "popup" with extra information to work.
The JS:
function init(){
var northSeaLonLat = [4.25, 52.05];
var centerWebMercator = ol.proj.fromLonLat(northSeaLonLat);
var tileLayer = new ol.layer.Tile({ source: new ol.source.OSM() });
markerLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [], projection: 'EPSG:3857' }) });
var map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.MousePosition({
coordinateFormat: ol.coordinate.createStringXY(3),
projection: 'EPSG:4326',
undefinedHTML: ' ',
className: 'custom-mouse-position',
target: document.getElementById('custom-mouse-position'),
})
]),
layers: [tileLayer, markerLayer],
target: 'map',
view: new ol.View({
projection: 'EPSG:3857',
center: centerWebMercator,
zoom: 7
})
});
// Add marker
var circle = new ol.style.Style({
image: new ol.style.Circle({
radius: 4,
fill: new ol.style.Fill({
color: 'rgba(200,0,0,0.9)',
}),
stroke: new ol.style.Stroke({
color: 'rgba(100,0,0,0.9)',
width: 2
})
})
});
coordinates = [[4.25, 52.05], [4.21, 52.01], [4.29, 52.29], [5.25, 52.05], [4.25, 51.05]];
for (i = 0; i < coordinates.length; i++) {
var feature = new ol.Feature(
new ol.geom.Point(ol.proj.transform(coordinates[i], 'EPSG:4326', 'EPSG:3857'))
);
feature.description = 'Coordinates: '+coordinates[i][0]+','+coordinates[i][1]+'\nBla';
feature.setStyle(circle);
markerLayer.getSource().addFeature(feature);
}
var element = document.getElementById('popup');
var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false
});
map.addOverlay(popup);
// display popup on click
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
if (feature) {
popup.setPosition(evt.coordinate);
$(element).popover({
'placement': 'top',
'html': true,
'content': feature.get('description')
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
}
The code I got from an example on the website: http://openlayers.org/en/v3.11.1/examples/icon.html
It works there but I can't get my version to work. Any idea why?
popover isn't part of OpenLayers but contained in Bootstrap: http://getbootstrap.com/javascript/#popovers
Also see the OpenLayers example on overlays: https://openlayers.org/en/latest/examples/overlay.html

Categories

Resources