How to change a open layer tile source? - javascript

I need to change the layer source for openlayer (using open weather api). Currently I am using the following code with no success.
let layer = this.map.getLayers().getArray()[2]
layer.setSource(forecastLayer)
Could you tell me what I am doing wrong?
What is the correct way to update the data source?
renderMapOpenLayer () {
let geo = this.props.geo
// render marker vector
let markerFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')) // TODO // take lat long from openweather api which should be sotred in the state
})
let markerSource = new ol.source.Vector({
features: [markerFeature]
})
let markerStyle = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0, 0],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'assets/pin.svg'
}))
})
let markerLayer = new ol.layer.Vector({
source: markerSource,
style: markerStyle
})
// render OpenStreetMap tile server
var tileLayer = new ol.layer.Tile({
source: new ol.source.OSM()
}, new ol.layer.Vector({
source: new ol.source.Vector({ features: [], projection: 'EPSG:4326' })
}))
// render cloud tile
let cloudLayer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: api.mapTemperature()
})
})
let forecastLayer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: api.forecast()
})
})
setTimeout(function () {
let layer = this.map.getLayers().getArray()[2]
layer.setSource(forecastLayer)
}.bind(this), 3000)
// create map
this.map = new ol.Map({
target: 'map',
layers: [
tileLayer,
markerLayer,
cloudLayer
],
view: new ol.View({
center: ol.proj.transform(geo, 'EPSG:4326', 'EPSG:3857'),
zoom: 4
})
})
}

layer.setSource should do the trick.
function onClick() {
layer.setSource(xyz2);
}
var xyz1 = new ol.source.XYZ({
url: 'https://server.arcgisonline.com/ArcGIS/rest/services/' +
'Demographics/USA_Percent_Over_64/MapServer/tile/{z}/{y}/{x}'
})
var xyz2 = new ol.source.XYZ({
url: 'https://server.arcgisonline.com/ArcGIS/rest/services/' +
'Demographics/USA_Percent_Under_18/MapServer/tile/{z}/{y}/{x}'
})
var layer = new ol.layer.Tile({
source: xyz1
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
layer
],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([0, 0]),
zoom: 3
})
});
Here is a working example:
layer.setSource Example

Related

Openlayer load GEOJSON from a variable instead of url

I've a map rapresentation, I want to add a layer based on a GEOJSON, but I don't want to read it directly from a GEOJSON file, instead I've a variable that contain the exact string of GEOJSON that I require, is possible to load it from a variable instead of an url?
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
title: 'bikesRented',
source: new ol.source.Vector({
url: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
format: new ol.format.GeoJSON()
}),
style: bikeStyle2
})
],
view: new ol.View({
center: ol.proj.fromLonLat([11.341868,44.494949]),
zoom: 14
})
});
You could read the features from your string and add them to the source
var source = new ol.source.Vector();
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
title: 'bikesRented',
source: source,
style: bikeStyle2
})
],
view: new ol.View({
center: ol.proj.fromLonLat([11.341868,44.494949]),
zoom: 14
})
});
source.addFeatures(
new ol.format.GeoJSON().readFeatures(geojsonstring, {
dataProjection: 'EPSG:4326',
featureProjection: map.getView().getProjection()
})
);
or you could use a data url and let OpenLayers load that
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
title: 'bikesRented',
source: new ol.source.Vector({
url: 'data:,' + encodeURIComponent(geojsonstring),
format: new ol.format.GeoJSON()
}),
style: bikeStyle2
})
],
view: new ol.View({
center: ol.proj.fromLonLat([11.341868,44.494949]),
zoom: 14
})
});

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

OpenLayers 5.3 : Why doesn't draw my poligon?

This is the code :
drawPoligon : function (vertices) {
debugger;
var map = peaMap;
var feature = new ol.Feature({
geometry: new ol.geom.Polygon([vertices])
});
var vectorSource= new ol.source.Vector({
features: [feature ]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
}
vertices = [1253906.08982072, 5430790.35506443, 1253935.16019819, 5430769.74133789, 1253951.90741865, 5430793.82802342, 1253955.42311216........]
Format of my coordinates array:
[
[1253906.08982072,5430790.35506443],
[1253935.16019819,5430769.74133789],
[1253951.90741865,5430793.82802342],
[1253955.42311216,5430798.88815272],
[1253953.91064413,5430800.28580152],
[1253952.03520923,5430801.40886153],
[1253945.88800332,5430791.50307534],
[1253936.62615957,5430797.3914173]
]
...The coordinates list isnt full. Only part of it for exposure.
The format [ [lon, lat], … ] is the correct one. With a bigger zoom you can see the result:
var osmLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var vertices = [
[1253906.08982072, 5430790.35506443],
[1253935.16019819, 5430769.74133789],
[1253951.90741865, 5430793.82802342],
[1253955.42311216, 5430798.88815272],
[1253953.91064413, 5430800.28580152],
[1253952.03520923, 5430801.40886153],
[1253945.88800332, 5430791.50307534],
[1253936.62615957, 5430797.3914173]
];
var feature = new ol.Feature({
geometry: new ol.geom.Polygon([vertices])
});
var vectorSource = new ol.source.Vector({
features: [feature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
width: 2,
color: [255, 0, 0]
})
})
});
var map = new ol.Map({
layers: [osmLayer, vectorLayer],
target: document.getElementById("map"),
view: new ol.View({
center: [1253950, 5430800],
zoom: 20
})
});

Openlayers source tileWMS? TypeError: a.addEventListener is not a function

I want to add features to my tile map, the problem ocurred when I try to use
ol.source.TileWMS
The error message is:
TypeError: a.addEventListener is not a function
However it works with
ol.source.OSM
My code:
var projection = new ol.proj.Projection({
code: 'EPSG:32719',
extent: [441867.78, 1116915.04, 833978.56, 10000000.00]
});
var extent = [576631.5686027373,8119272.722829757,655823.9357532839,8286730.359291008];
var wmsSource = new ol.source.TileWMS({
url: 'http://192.168.5.94:8080/geoserver/wms',
params: {'LAYERS': 'layer'},
ratio: 1,
serverType: 'geoserver'
});
var wmsLayers = [
new ol.layer.Tile({
extent: extent,
source: wmsSource
})
];
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector({wrapX: false});
var vector = new ol.layer.Vector({
source: source
});
var view = new ol.View({
projection: projection,
center: [593169.72792, 8174979.55243],
//center: ol.proj.fromLonLat([-16.5088, -68.1388], projection),
extent: extent,
zoom: 12
});
var map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.ScaleLine()
]),
layers: [wmsLayers, vector],
target: 'map',
view: view
});
var draw; // global so we can remove it later
function addInteraction(){
draw = new ol.interaction.Draw({
source: source,
type: 'Point'
});
map.addInteraction(draw);
}
map.on('singleclick', function(evt) {
var coordinate = map.getEventCoordinate(evt.originalEvent);
console.log(coordinate);
document.getElementById('latitud').value = coordinate[0];
document.getElementById('longitud').value = coordinate[1];
addInteraction();
});
addInteraction();
Just change this line to change my layer, when I use OSM, everything is ok... But when I use TileWMS the error appear
layers: [wmsLayers, vector],
Is there a conflict with TileWMS and Vector source?
ol.Map.layers expects an array of layers - your first object in the array is an array.
Try this:
var wmsLayer = new ol.layer.Tile({
extent: extent,
source: wmsSource
});
var map = new ol.Map({
layers: [wmsLayer, vector],
target: 'map',
view: view
});

Openlayers 3 circles from geojson not working with layer tile source different from TileWMS

I am working with openlayers 3 with a layer from mapbox or openstreetmap and I need to draw some circles on it.
I am able to print the circles with a view with a projection EPSG:4326, but then I have no map. Changing the projection with a transform the map is displayed, but the points are all together. The only way I am made it work is using TileWMS as a source, but I am not able to use it in production environment
Here is my code:
version 1: working with TileWMS
var source = new ol.source.GeoJSON({
url: 'geojson url'
});
var pointsLayer = new ol.layer.Vector({
source: source,
style: new ol.style.Style({
image: new ol.style.Circle({
radius: 15,
fill: new ol.style.Fill({color: 'rgba(170,33,33, 0.8)'}),
stroke: new ol.style.Stroke({color: 'rgba(170,33,33, 0.3)', width: 8})
})
})
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
title: "Global Imagery",
source: new ol.source.TileWMS({
url: 'http://maps.opengeo.org/geowebcache/service/wms',
params: {LAYERS: 'bluemarble', VERSION: '1.1.1'}
})
}),
pointsSource
],
view: new ol.View({
projection: 'EPSG:4326',
center: [-82.3, -10.65],
zoom: 3
})
});
This is the result
Using mapbox or osm, failing:
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://api.tiles.mapbox.com/v4/XXXXX.kcp9cpdn/{z}/{x}/{y}.png?access_token=token'
})
}),
/*
new ol.layer.Tile({
source: new ol.source.OSM()
}),*/
pointsSource
],
view: new ol.View({
projection: 'EPSG:4326',
center: [-82.3, -10.65],
zoom: 3
})
});
This is the result
And finally, changing the view the map is displayed but the circles
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://api.tiles.mapbox.com/v4/XXXXX.kcp9cpdn/{z}/{x}/{y}.png?access_token=token'
})
}),
/*
new ol.layer.Tile({
source: new ol.source.OSM()
}),*/
pointsSource
],
view: new ol.View({
center: ol.proj.transform([-82.3, -10.65], 'EPSG:4326', 'EPSG:3857'),
zoom: 3
})
});
And the result
Is there a way to make this work?
Thanks in advance.
I found the solution, here it is for it is helping anyone
Following this answer in gis stackexchange https://gis.stackexchange.com/a/118818/42868 There is an unstable option for the ol.source.GeoJSON object, so adding it in this way made it work
var source = new ol.source.GeoJSON({
url: 'geojson url',
projection: 'EPSG:3857'
});

Categories

Resources