I am trying to load the big GeoJSON file using the OpenLayers. The problem is after loading it then the complete map becomes slow to do any other operation. So my question is there anyway to load a geojson file as a Tile rather ?
Here is my code:
function addGEOJSONLayer() {
console.log("reached");
var url= 'http://172.61.25.51:8080/test/ab.json';
var vectorSource = new ol.source.Vector({
strategy: ol.loadingstrategy.bbox,
projection: 'EPSG:4326',
loader: function(extent, resolution, projection) {
$.ajax(url).then(function(response) {
console.log(response);
var features = new ol.format.GeoJSON().readFeatures(response);
vectorSource.addFeatures(features);
});
}
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: function (feature, resolution) {
return [new ol.style.Style({
stroke: new ol.style.Stroke({
width: 1,
color: feature.get('stroke')
}),
fill: new ol.style.Fill({
color: feature.get('fill'),
})
})];
}
});
var ext = vectorLayer.getSource().getExtent();
map.getView().fit(ext, map.getSize());
map.addLayer(vectorLayer);
}
Any suggestions will be of great help! Thanks
Related
how can i add a KML layer to the switcher by ol-ext Viglino?
When I add:
var vectorSource = new ol.layer.Vector({
source: new ol.source.Vector({
url: "IG1.kml",
format: new ol.format.KML()
})
The layer does not appear on the map.
To appear in the layer switcher the layer must have a title property
var vectorSource = new ol.layer.Vector({
title: "KML Layer",
source: new ol.source.Vector({
url: "IG1.kml",
format: new ol.format.KML()
})
})
If the layer is not appearing on the map check that .kml extension is enabled in your server MIME types.
Try :
import KML from 'ol/format/KML';
import VectorSource from 'ol/source/Vector';
import {Vector as VectorLayer} from 'ol/layer';
const vector = new VectorLayer({
source: new VectorSource({
url: 'IG1.kml',
format: new KML(),
}),
});
I am new to openlayers3. I am showing point as a image but I want to change color of image dynamically.Is it possible in openlayers3 or have any other facility like canvas in openlayers3?
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'data/icon.png'
}))
});
Taking Icon Colors as starting point where they use a transparent PNG with ol.Color option to have multiple color dots I've tried to change the colors like this without success...
var london = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.12755, 51.507222]))
});
london.setStyle(new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
color: '#ff0000',
crossOrigin: 'anonymous',
src: 'https://openlayers.org/en/v4.1.1/examples/data/dot.png'
}))
}));
var vectorSource = new ol.source.Vector({
features: [london]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var rasterLayer = new ol.layer.Tile({
source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: ''
})
});
var map = new ol.Map({
layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'),
view: new ol.View({
center: ol.proj.fromLonLat([2.896372, 44.60240]),
zoom: 3
})
});
map.on('singleclick', function (event) { // Use 'pointermove' to capture mouse movement over the feature
map.forEachFeatureAtPixel(event.pixel, function (feature, layer) {
/* Get the current image instance and its color */
var image = feature.getStyle().getImage();
console.log(image.getColor());
/* Color gets stored in image.i, but there's no setter */
console.log(image.i);
/* Trying to force the color change: */
image.i = [0, 255, 0, 1];
/* Dispatch the changed() event on layer, to force styles reload */
layer.changed();
console.log(image.getColor()); // Logs new color, but it doesn't work...
});
});
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.1.1/build/ol.js"></script>
<div id="map" class="map"></div>
See how you can retrieve an icon's color like this:
var image = feature.getStyle().getImage(),
color = image.getColor(); // returns [R, G, B, alpha]
but there's no setColor() method, so there's no way to change the color in runtime...
EDIT: Reviewing again your question and your code, I've noticed you never set a color for your icon, so maybe you don't really want to actually change the color in response to an event but just set a color. If that's what you want, then it's easy:
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'data/icon.png',
color: '#ff0000' // allows HEX as String or RGB(a) as Array
}))
});
See: http://openlayers.org/en/latest/apidoc/ol.style.Icon.html
I'm trying to force a vector layer in OpenLayers 3 to periodically reload its data from a GeoJSON source. The GeoJSON source changes from time to time.
After many different attempts using different methods, I think this is the closest I've managed to get so far:
$(document).ready(function(){
map.once("postcompose", function(){
//start refreshing each 3 seconds
window.setInterval(function(){
var source = testLayer.getSource();
var params = source.getParams();
params.t = new Date().getMilliseconds();
source.updateParams(params);
}, 3000);
});
});
However this is giving me the following (every 3 seconds of course):
Uncaught TypeError: source.getParams is not a function
Here's all of the other code I'm using to load and display the GeoJSON file. The other layers in the map are loaded in the same way:
var testSource = new ol.source.Vector({
url: '/js/geojson/testfile.geojson',
format: new ol.format.GeoJSON()
});
...
window.testLayer = new ol.layer.Vector({
source: testSource,
style: function(feature, resolution) {
var style = new ol.style.Style({
fill: new ol.style.Fill({color: '#ffffff'}),
stroke: new ol.style.Stroke({color: 'black', width: 1}),
text: new ol.style.Text({
font: '12px Verdana',
text: feature.get('testvalue'),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.1)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 1)',
width: 1
})
})
});
return style
}
});
...
var olMapDiv = document.getElementById('olmap');
var map = new ol.Map({
layers: [paddocksLayer,zonesLayer,structuresLayer,roadsLayer,testLayer],
interactions: ol.interaction.defaults({
altShiftDragRotate: false,
dragPan: false,
rotate: false
}).extend([new ol.interaction.DragPan({kinetic: null})]),
target: olMapDiv,
view: view
});
view.setZoom(1);
view.setCenter([0,0]);
I read somewhere else that getParams simply doesn't work on vector layers, so this error wasn't entirely unexpected.
Is there an alternative method which will reload (not just re-render) a vector layer?
Thanks in advance. I must also apologise in advance as I'll need really specific guidance with this - I'm very new to JS and OpenLayers.
Gareth
(fiddle)
You can achieve this with a custom AJAX loader (when you pass url to ol.source.Vector this is AJAX as well). Then you can reload your JSON file as you will.
You can use any AJAX library you want but this is as simple as:
var utils = {
refreshGeoJson: function(url, source) {
this.getJson(url).when({
ready: function(response) {
var format = new ol.format.GeoJSON();
var features = format.readFeatures(response, {
featureProjection: 'EPSG:3857'
});
source.addFeatures(features);
source.refresh();
}
});
},
getJson: function(url) {
var xhr = new XMLHttpRequest(),
when = {},
onload = function() {
if (xhr.status === 200) {
when.ready.call(undefined, JSON.parse(xhr.response));
}
},
onerror = function() {
console.info('Cannot XHR ' + JSON.stringify(url));
};
xhr.open('GET', url, true);
xhr.setRequestHeader('Accept','application/json');
xhr.onload = onload;
xhr.onerror = onerror;
xhr.send(null);
return {
when: function(obj) { when.ready = obj.ready; }
};
}
};
I have a ol 3.10.1 map where the goal is to redraw the features of a layer dynamically. On the road to get there, I'm using the source.clear() function. The strange thing is that the source.clear() actually clear the features from the layer at the current zoom level, but while zooming in or out the features are still there. Am I using the source.clear() function the correct way? Please find bellow the code snippet which I'm using for testing purposes.
var image = new ol.style.Circle({
radius: 5,
fill: null,
stroke: new ol.style.Stroke({color: 'red', width: 1})
});
var styles = {
'Point': [new ol.style.Style({
image: image
})]};
var styleFunction = function(feature, resolution) {
return styles[feature.getGeometry().getType()];
};
var CITYClusterSource = new ol.source.Cluster({
source: new ol.source.Vector({
url: 'world_cities.json',
format: new ol.format.GeoJSON(),
projection: 'EPSG:3857'
}),
})
var CITYClusterLayer = new ol.layer.Vector({
source: CITYClusterSource,
style: styleFunction
});
setTimeout(function () { CITYClusterSource.clear(); }, 5000);
var map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
CITYClusterLayer
],
view: new ol.View({
center: ol.proj.transform([15.0, 45.0], 'EPSG:4326', 'EPSG:3857'),
zoom:3
})
});
I'm using the setTimout() function to have the features visible for some seconds, before they are supposed to be cleared.
Please advice.
UPDATE: http://jsfiddle.net/jonataswalker/ayewaz87/
I forgot, OL will load your features again and again, for each resolution. So if you want to remove once and for all, use a custom loader, see fiddle.
Your source is asynchronously loaded, so set a timeout when it's ready:
CITYClusterSource.once('change', function(evt){
if (CITYClusterSource.getState() === 'ready') {
// now the source is fully loaded
setTimeout(function () { CITYClusterSource.clear(); }, 5000);
}
});
Note the once method, you can use on instead of it.
im learing OpenLayers 3 and i am trying to assign an png image to the logo attribute of the layer.Vector.source like this:
var vectorSpeedLimit40 = new ol.layer.Vector({
title: 'speedlimit40',
source: new ol.source.Vector({
url: 'gpx/Fotoboks_40.gpx',
format: new ol.format.GPX({
extraStyles: false
}),
logo: '/imgs/lc.png'
})
});
var rasterLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [rasterLayer, vectorSpeedLimit40],
target: document.getElementById('map-canvas'),
view: new ol.View({
center: [0, 0],
zoom: 3
})
});
Where i thought this would show instances of the png, it shows small blue circles instead like this:
I have checked, double checked, triple checked and the path is correct relative to the client.
What am i doing wrong? Thanks!
To assign a specific image to a vectorLayer with a GPX source you have to assign the image property a new ol.style.Icon with the src attribute to the image like this:
var vectorSource = new ol.source.Vector({
// Specify that the source is of type GPX
format: new ol.format.GPX(),
// Here you specify the path to the image file
url: 'gpx/source.gpx'
})
var vectorStyle = new ol.style.Style({
// Set the image attribute to a new ol.style.Icon
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
scale: 0.2,
// Here you specify the path to the image file
src: 'imgs/image.png'
}))
})
var vectorLayer = new ol.layer.Vector({
// Here you specify the source and style attributes of the ol.layer.Vector to the ones that are made above
source: vectorSource,
style: vectorStyle
});
// Then add it to the map
map.addLayer(vectorLayer);