Openlayer load GEOJSON from a variable instead of url - javascript

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

Related

How to use MousePosition at Openlayer 5 with vanilla js?

What's wrong with my code? I want to get coordinates with mousePosition. I use openlayer v5.
var map = new ol.Map({
target: 'map2',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([116.041389, 3.073093]),
zoom: 7.3
})
});
var mousePositionControl = new ol.MousePosition({
coordinateFormat: createStringXY(2),
projection: 'EPSG:4326',
className: 'custom-mouse-position',
target: document.getElementById('mouse-position'),
undefinedHTML: ' '
});
executing the above code will get an
"ReferenceError: createStringXY is not defined" error.

How to change a open layer tile source?

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

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

GeoJSON projection of external file vs. internal object

I have this external GeoJSON file:
{"type": "FeatureCollection", "features": [ {"type":"Feature", "id":382, "properties":{"name":"Foo","description":"Bar"}, "geometry":{"type":"MultiPolygon","coordinates":[[[[100.51731551305,14.018177133438],[100.517959243205,14.0188303173272],[100.517133122834,14.0194652831494],[100.516628867536,14.0198920624699],[100.51755154744,14.0206831634993],[100.521199351693,14.0200794287498],[100.518087989239,14.0167692686143],[100.517798310678,14.0169176022848],[100.51731551305,14.018177133438]]]]}} ] }
If I use it like this, it's located properly:
var vectorSource = new ol.source.Vector({
url: 'data.geojson',
format: new ol.format.GeoJSON(),
projection : 'EPSG:4326',
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
}),
vectorLayer
],
view: new ol.View({
center: ol.proj.transform([100.514,14.012], 'EPSG:4326', 'EPSG:3857'),
zoom: 11
})
});
However, if I try to insert the GeoJSON directly as an object, the layer is displayed as a tiny dot at position 0, 0:
var geojsonObject = {"type": "FeatureCollection", "features": [ {"type":"Feature", "id":382, "properties":{"name":"Foo","description":"Bar"}, "geometry":{"type":"MultiPolygon","coordinates":[[[[100.51731551305,14.018177133438],[100.517959243205,14.0188303173272],[100.517133122834,14.0194652831494],[100.516628867536,14.0198920624699],[100.51755154744,14.0206831634993],[100.521199351693,14.0200794287498],[100.518087989239,14.0167692686143],[100.517798310678,14.0169176022848],[100.51731551305,14.018177133438]]]]}} ] };
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject),
projection : 'EPSG:4326'
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
}),
vectorLayer
],
view: new ol.View({
center: ol.proj.transform([100.514,14.012], 'EPSG:4326', 'EPSG:3857'),
zoom: 11
})
});
What's wrong here?
In the second example, add projection options to the readFeatures call:
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject,
{dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857'}),

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