Openlayers Set property to KML vector layer markers? - javascript

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

Related

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 3: Show vector labels on hover

I'm trying to find a way to display labels on OpenLayers vector features only when the mouse hovers over the feature's icon. I've found a few examples of similar things but nothing that quite does what I need to do. It seems to me like it would be fairly simple but I just can't work out how to start.
This is what my feature style code looks like (one example of several). Note that I'm bringing in the feature data from a few GeoJSON files, hence the feature.get(...)s in the color sections:
if (feature.get('level_pc') < 35 ) {
var style = new ol.style.Style({
fill: new ol.style.Fill({color: feature.get('shapefill')}),
stroke: new ol.style.Stroke({color: feature.get('shapestroke')}),
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [16, 16],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 0.75,
src: '/icons/aws-red.png'
})),
text: new ol.style.Text({
font: '12px Roboto',
text: feature.get('label'),
fill: new ol.style.Fill({
color: feature.get('textfill')
}),
stroke: new ol.style.Stroke({
color: feature.get('textstroke'),
width: 1
})
})
});
return style
} else { ...
I'm really hoping that there's a way to insert some code into the style definition that creates the hover interaction, rather than having to create a duplicate of every style and then write some extra code that switches between the hover/non-hover styles as necessary. Maybe it could be by way of setting the alpha value in the text color to 255 on mouseover and 0 at other times. Perhaps I'm being too optimistic.
Does anyone have any ideas or examples I could check out?
Thanks,
Gareth
EDIT: Thanks to Jose I'm much closer to the goal now. My original code has changed somewhat since I first asked the question. I'm now applying styles to each feature through a function which reads the name of the icon file from GeoJSON data. For example gates are displayed with a 'gate-open' or 'gate-closed' icon and silos with a 'silo-high', 'silo-medium' or 'silo-low' icon. The correct icons and text are displaying on hover for all features, which is great - it's just that when I'm not hovering over the icons, the incorrect icon is displaying - it's showing the 'silo-low' icon for all features. When I hover over an icon it shows the correct icon, then reverts back when I'm no longer hovering.
Here's (the important bits of) my updated code:
var structuresStyleHover = function(feature, resolution) {
style = new ol.style.Style({
fill: new ol.style.Fill({color: feature.get('shapefill')}),
stroke: new ol.style.Stroke({color: feature.get('shapestroke')}),
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [16, 16],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
src: '/icons/'+feature.get('icon')+'-'+feature.get('status').toLowerCase()+'.png'
})),
text: new ol.style.Text({
font: '12px Roboto',
text: feature.get('label'),
fill: new ol.style.Fill({
color: feature.get('textfill')
}),
stroke: new ol.style.Stroke({
color: feature.get('textstroke'),
width: 1
})
})
})
return style;
};
var styleCache = {};
var styleFunction = function(feature,resolution) {
var radius = 16;
var style = styleCache[radius];
if (!style) {
style = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [16, 16],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 0.5,
src: '/icons/'+feature.get('icon')+'-'+feature.get('status').toLowerCase()+'.png'
})),
});
styleCache[radius] = style;
}
return style;
};
var structuresLayer = new ol.layer.Vector({
source: structuresSource,
style: styleFunction
});
...
var map = new ol.Map({
layers: [paddocksLayer,structuresLayer],
interactions: ol.interaction.defaults({
altShiftDragRotate: false,
dragPan: false,
rotate: false
}).extend([new ol.interaction.DragPan({kinetic: null})]),
target: olMapDiv,
view: view
});
...
map.on('pointermove', function(evt) {
if (evt.dragging) {
return;
}
structuresLayer.getSource().getFeatures().forEach(f=>{
f.setStyle(styleFunction);
});
var pixel = map.getEventPixel(evt.originalEvent);
map.forEachFeatureAtPixel(pixel,function(feature,resolution) {
feature.setStyle(structuresStyleHover(feature,resolution));
return feature;
});
});
I'm not getting any errors - it's just not showing the correct icon unless the mouse is hovering over the icon.
I'm sure I'm missing something really obvious, but I can't work it out. Any ideas please?
You can use setStyle:
var mystyle = new ol.style.Style({
fill: new ol.style.Fill({color: '#00bbff'}),
stroke: new ol.style.Stroke({color: '#fff'}),
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [16, 16],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
scale : 0.1,
opacity: 1,
src: 'http://2.bp.blogspot.com/_Sdh3wYnDKG0/TUiIRjXEimI/AAAAAAAAQeU/bGdHVRjwlhk/s1600/map+pin.png'
})),
text: new ol.style.Text({
font: '12px Roboto',
text: 'AAAAAAAAAAAAAAA',
fill: new ol.style.Fill({
color: '#ffbb00'
}),
stroke: new ol.style.Stroke({
color: '#000',
width: 1
})
})
});
var styleCache = {};
var styleFunction = function(feature) {
var radius = 3;
var style = styleCache[radius];
if (!style) {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
fill: new ol.style.Fill({
color: 'rgba(255, 153, 0, 0.4)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(255, 204, 0, 0.2)',
width: 1
})
})
});
styleCache[radius] = style;
}
return style;
};
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'http://openlayers.org/en/v3.17.1/examples/data/kml/2012_Earthquakes_Mag5.kml',
format: new ol.format.KML({
extractStyles: false
})
}),
style: styleFunction
});
var raster = new ol.layer.Tile({
source: new ol.source.Stamen({
layer: 'toner'
})
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
map.on('pointermove', function(evt) {
if (evt.dragging) {
return;
}
vector.getSource().getFeatures().forEach(f=>{
f.setStyle(styleFunction);
});
var pixel = map.getEventPixel(evt.originalEvent);
map.forEachFeatureAtPixel(pixel,function(feature) {
feature.setStyle(mystyle);
return feature;
});
});
#map {
position: relative;
}
<title>Earthquakes in KML</title>
<link rel="stylesheet" href="http://openlayers.org/en/v3.17.1/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.17.1/build/ol.js"></script>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="map" class="map"></div>

OpenLayers Remove Layer from map

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

OpenLayers 3 - Z-index of features on highlights

I have some troubles with z-index on OpenLayers 3 when i want to highlight a feature.
I create a GeoJSON shape of a country, add some marker on top, and i want the shape color change when i hover on.
But, when the color change, the shape hide my markers.
I try to put zIndex style on the hightlight style but this doesn't change anything...
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})],
controls: ol.control.defaults({
attributionOptions: ({
collapsible: false
})
}),
target: 'map',
view: new ol.View({
center: [631965.84, 4918890.2],
zoom: 3
})
});
var vector = new ol.layer.Vector({
source: new ol.source.Vector({}),
style: new ol.style.Style({
zIndex: 1,
stroke: new ol.style.Stroke({
color: '#589CA9',
width: 3
}),
fill: new ol.style.Fill({
color: '#589CA9'
})
})
});
map.addLayer(vector);
var selectPointerMove = new ol.interaction.Select({
condition: ol.events.condition.pointerMove,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#EF7F01',
width: 3
}),
zIndex: 1,
fill: new ol.style.Fill({
color: '#EF7F01'
})
})
});
map.addInteraction(selectPointerMove);
var feature = new ol.format.GeoJSON().readFeature(Some_GeoJSON_Coordinate, {
dataProjection: ol.proj.get('EPSG:4326'),
featureProjection: ol.proj.get('EPSG:3857')
});
vector.getSource().addFeature(feature);
iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([5, 44],"EPSG:4326", 'EPSG:3857')),
type:"marker"
});
var iconStyle = new ol.style.Style({
zIndex:2,
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor:[0.5,1],
scale:0.1,
src: 'https://lh4.ggpht.com/Tr5sntMif9qOPrKV_UVl7K8A_V3xQDgA7Sw_qweLUFlg76d_vGFA7q1xIKZ6IcmeGqg=w300'
}))
});
iconFeature.setStyle(iconStyle);
vector.getSource().addFeature(iconFeature)
I create a JSFiddle of my issue : http://jsfiddle.net/a1zb5kzf/1/
Thanks you in advance for your help
I found a solution.
According to the Select Interaction documentation, it's don't just apply an other Style but move your feature on a temporary overlay. And so, zIndex doesn't work because features aren't on the same layer anymore.
So, to get my highlight comportement and keep my feature on the same layer, i watch the pointermove event, and apply style if necessary. Just before, i memorized the feature, and reapply default style on it
cartoCtrl.map.on("pointermove", function (evt) {
var feature = cartoCtrl.map.forEachFeatureAtPixel(evt.pixel,
function (feature) {
return feature;
});
if (feature && feature.getProperties().type != "marker") {
cartoCtrl.lastHighlitedFeature = feature;
feature.setStyle(highlightStyle)
}));
} else {
if(cartoCtrl.lastHighlitedFeature){
cartoCtrl.lastHighlitedFeature.setStyle(defautlStyle);
cartoCtrl.lastHighlitedFeature = false;
}
}
});

how to add markers with OpenLayers 3

I'm trying to add makers on a OpenLayers 3 map.
The only example I have found is this one in the OpenLayers example list.
But the example uses ol.Style.Icon instead of something like OpenLayers.Marker in OpenLayers 2.
First Question
The only difference would be that you have to set the image Url but is it the only way to add a marker?
Also OpenLayers 3 doesn't seem to come with marker images so it would make sense if there's no other way than ol.Style.Icon
Second Question
It would be really nice if someone could give me an example of a function to add markers or icons after the map is loaded.
From what I understand in the example, they create a layer for the icon
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')),
name: 'Null Island',
population: 4000,
rainfall: 500
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'data/icon.png'
}))
});
iconFeature.setStyle(iconStyle);
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
Then they set the icon layer when they initialize the map
var map = new ol.Map({
layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vectorLayer],
target: document.getElementById('map'),
view: new ol.View2D({
center: [0, 0],
zoom: 3
})
});
If I want to add many markers, do I have to create 1 layer for each marker?
How could I add many markers to a layer? I can't figure out how this part would look
like
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
Thank you
Q1. Markers are considered deprecated in OpenLayers 2, though this isn't very obvious from the documentation. Instead, you should use an OpenLayers.Feature.Vector with an externalGraphic set to some image source in its style. This notion has been carried over to OpenLayers 3, so there is no marker class and it is done as in the example you cited.
Q2. The ol.source.Vector takes an array of features, note the line, features: [iconFeature], so you would create an array of icon features and add features to that, eg:
var iconFeatures=[];
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326',
'EPSG:3857')),
name: 'Null Island',
population: 4000,
rainfall: 500
});
var iconFeature1 = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([-73.1234, 45.678], 'EPSG:4326',
'EPSG:3857')),
name: 'Null Island Two',
population: 4001,
rainfall: 501
});
iconFeatures.push(iconFeature);
iconFeatures.push(iconFeature1);
var vectorSource = new ol.source.Vector({
features: iconFeatures //add an array of features
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'data/icon.png'
}))
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyle
});
Obviously, this could be more elegantly handled by putting all of the ol.Feature creation inside a loop based on some data source, but I hope this demonstrates the approach. Note, also, that you can apply a style to the ol.layer.Vector so that it will be applied to all features being added to the layer, rather than having to set the style on individual features, assuming you want them to be the same, obviously.
EDIT: That answer doesn't seem to work. Here is an updated fiddle that works by adding the features (icons) to the empty vector source in a loop, using vectorSource.addFeature and then adds the whole lot to the layer vector afterwards. I will wait and see if this works for you, before updating my original answer.
there's a good tutorial at: http://openlayersbook.github.io
not tested but may helpful
var features = [];
//iterate through array...
for( var i = 0 ; i < data.length ; i++){
var item = data[i]; //get item
var type = item.type; //get type
var longitude = item.longitude; //coordinates
var latitude = item.latitude;
/*....
* now get your specific icon...('..../ic_customMarker.png')
* by e.g. switch case...
*/
var iconPath = getIconPath(type);
//create Feature... with coordinates
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([longitude, latitude], 'EPSG:4326',
'EPSG:3857'))
});
//create style for your feature...
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: iconPath
}))
});
iconFeature.setStyle(iconStyle);
features.push(iconFeature);
//next item...
}
/*
* create vector source
* you could set the style for all features in your vectoreSource as well
*/
var vectorSource = new ol.source.Vector({
features: features //add an array of features
//,style: iconStyle //to set the style for all your features...
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
var exampleLoc = ol.proj.transform(
[131.044922, -25.363882], 'EPSG:4326', 'EPSG:3857');
var map = new ol.Map({
target: 'map',
renderer: 'canvas',
view: new ol.View2D({
projection: 'EPSG:3857',
zoom: 3,
center: exampleLoc
}),
layers: [
new ol.layer.Tile({source: new ol.source.MapQuest({layer: 'osm'})})
]
});
map.addOverlay(new ol.Overlay({
position: exampleLoc,
element: $('<img src="resources/img/marker-blue.png">')
.css({marginTop: '-200%', marginLeft: '-50%', cursor: 'pointer'})
.tooltip({title: 'Hello, world!', trigger: 'click'})
}));
map.on('postcompose', function(evt) {
evt.vectorContext.setFillStrokeStyle(
new ol.style.Fill({color: 'rgba(255, 0, 0, .1)'}),
new ol.style.Stroke({color: 'rgba(255, 0, 0, .8)', width: 3}));
evt.vectorContext.drawCircleGeometry(
new ol.geom.Circle(exampleLoc, 400000));
});
var exampleKml = new ol.layer.Vector({
source: new ol.source.KML({
projection: 'EPSG:3857',
url: 'data/example.kml'
})
});
map.addLayer(exampleKml);
We just finished updating our website NUFOSMATIC from ol2 to ol6. Both the ol2 and ol3 code is on the site. This includes Matt Walker's ol-layerswitcher https://github.com/walkermatt replacing the missing ol2 layerswitcher. We actually updated three map applications; HEATMAP replaces the Patrick Wied (http://www.patrick-wied.at) ol2 heatmap with the native ol6 heatmap.
Only took 6 days. Wonder why we waited this long... oh, yeah, we have day jobs...

Categories

Resources