OpenLayers3 GeoJSON parsing wrong argument? - openlayers-3

after drawing features to OpenLayers map (map overlay) I want to parse features to be able to send it.
Problem is that when I call getArray() it works and without getArray it doesn't. Shouldn't parse.writeFeatures get as paramater featureOverlay.getFeatures() and not featureOverlay.getFeatures().getArray()?
$.FooBarNS.featureOverlay = new ol.FeatureOverlay({
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
$.FooBarNS.featureOverlay.setMap(map);
$('#save_polygon').click( function(){
var parser = new ol.format.GeoJSON();
//features = $.FooBarNS.features;
var features = $.FooBarNS.featureOverlay.getFeatures().getArray();
console.log(features);
var featuresGeoJSON = parser.writeFeatures(features, {'dataProjection':'EPSG:4326','featureProjection':'EPSG:3857'});
console.log(featuresGeoJSON);
$.ajax({
type: 'POST',
url: 'http://gis.FooBar.com/testpolygon/',
dataType: 'json',
//contentType: 'application/json;charset=utf-8',
data: featuresGeoJSON
}).then(function(response) {
//console.log(response);
});
});

Check the API docs: http://openlayers.org/en/v3.5.0/apidoc/ol.format.GeoJSON.html#writeFeatures
writeFeatures takes an Array of ol.Feature so that's what you need to pass in.

Related

OpenLayers 6 on Rails target.addEventListener is not a function

i start from the scratch to build a Rails 6 Application with Openlayers 6.1.1. with Webpacker and Turbolinks. Many things are working fine, also with turbolinks.
But one thing will not work fine: Openlayers.
I add openlayers with yarn an it is basically working. So i can create a map as i expected, but i am not able to add a VectorLayer. If i do this i will get a console message with :
target.addEventListener is not a function
I mean i am importing all required libs. In my application.js
require("#openlayers/pepjs")
require("ol")
In my map.js
import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import MVT from 'ol/format/MVT';
import View from 'ol/View';
import GeoJSON from 'ol/format/GeoJSON';
import Circle from 'ol/geom/Circle';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
//import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
And my map object:
var vectorLayer = new VectorLayer({
source: new VectorSource({
url: 'v1/track/journey',
format: new GeoJSON()
}),
});
var OSMMap = new TileLayer({
source: new OSM({
attributions: [
'(c) OpenStreetMap'
],
opaque: false,
url: 'http://10.232.200.17/tiles/osm/{z}/{x}/{y}.png'
})
});
// OL Test
var map = new Map({
layers: [
OSMMapHLC1,
VectorLayer
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});
I tried it without turbolinks
I added pepjs
I added jquery manually
I tried Leaflet. Result VectorLayers an Realtime Plugin working fine.
Hint. I have to use Openlayers not Leaflet.
Many thanks to everyone who can help.
Stacktrace
Regards Marco
try to replace this on your code:
var map = new Map({
layers: [
OSMMap,
vectorLayer
],
thank you so much for your answer. i thinks this was a copy-paste failure from my side. I had try so many things that my code was messed up. So i start from the scratch an now it is working, So i will show my code here:
It is mandatory to put all imports outside the turbolinks, everything else should be inside the turbolinks load() function:
import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import View from 'ol/View';
import GeoJSON from 'ol/format/GeoJSON';
import Circle from 'ol/geom/Circle';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
//import { toPng } from 'html-to-image';
$(document).on('turbolinks:load', function() {
var exportOptions = {
filter: function(element) {
return element.className ? element.className.indexOf('ol-control') === -1 : true;
}
};
document.getElementById('export-png').addEventListener('click', function() {
map.once('rendercomplete', function() {
toPng(map.getTargetElement(), exportOptions)
.then(function(dataURL) {
var link = document.getElementById('image-download');
link.href = dataURL;
link.click();
});
});
map.renderSync();
});
var image = new CircleStyle({
radius: 5,
fill: null,
stroke: new Stroke({ color: 'red', width: 1 })
});
var styles = {
'Point': new Style({
image: image
}),
'LineString': new Style({
stroke: new Stroke({
color: 'green',
width: 1
})
}),
'MultiLineString': new Style({
stroke: new Stroke({
color: 'green',
width: 1
})
}),
'MultiPoint': new Style({
image: image
}),
'MultiPolygon': new Style({
stroke: new Stroke({
color: 'yellow',
width: 1
}),
fill: new Fill({
color: 'rgba(255, 255, 0, 0.1)'
})
}),
'Polygon': new Style({
stroke: new Stroke({
color: 'blue',
lineDash: [4],
width: 3
}),
fill: new Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}),
'GeometryCollection': new Style({
stroke: new Stroke({
color: 'magenta',
width: 2
}),
fill: new Fill({
color: 'magenta'
}),
image: new CircleStyle({
radius: 10,
fill: null,
stroke: new Stroke({
color: 'magenta'
})
})
}),
'Circle': new Style({
stroke: new Stroke({
color: 'red',
width: 2
}),
fill: new Fill({
color: 'rgba(255,0,0,0.2)'
})
})
};
var styleFunction = function(feature) {
return styles[feature.getGeometry().getType()];
};
var vectorLayer = new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),
url: 'v1/track?journey=#####'
}),
style: styleFunction
});
var map = new Map({
layers: [
new TileLayer({
source: new OSM()
}),
vectorLayer
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});
});

Openlayers 3 : How to change Geojson Icon src so it won't override other geojson types?

I'm able to change src of an icon when loading Point/MultiPoint Geojson, in this way:
that.geojsonLayers[index] = new that.openlayers.ol.layer.Vector({
source: new that.openlayers.ol.source.Vector({
format: new that.openlayers.ol.format.GeoJSON(),
url: url
}),
style: new that.openlayers.ol.style.Style({
image: new that.openlayers.ol.style.Icon({
src: 'http://mapmip.webiks.com/assets/Markers/marker-icon-blue.png'
})
})
but then I can't load other types of Geojson - Polygons are not being loaded at all, and Geometry Collection (which composed from icon and lines) is load only the icon.
What is the way to change the icon src so it won't override the other geojson type ?
You may use a style function to verify the geometry type you need to style. Setting an icon for styling a polygon is not correct.
Check this
1.Declare your style
var myMultiStyle = {
//here replace with your icon style
'Point': new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({
color: 'rgba(255,255,0,0.4)'
}),
radius: 5,
stroke: new ol.style.Stroke({
color: '#ff0',
width: 1
})
})
}),
'LineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#f00',
width: 3
})
}),
'Polygon': new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0,255,255,0.5)'
}),
stroke: new ol.style.Stroke({
color: '#0ff',
width: 1
})
})
};
Create a style function
function myStyleFunction(feature,resolution){
return myMultiStyle[feature.getGeometry().getType()];
}
Asign the style function to your vector source
that.geojsonLayers[index] = new that.openlayers.ol.layer.Vector({
source: new that.openlayers.ol.source.Vector({
format: new that.openlayers.ol.format.GeoJSON(),
url: url
}),
style: myStyleFunction
})
Check this official example to see the result.

GeoJSON data not displayed on a vector layer

I'm trying to display a vector layer to show a set of geojson features.
When I try and add the layer though I get an error in the ol.js library "k.xd is not a function"
var geoData = {"type":"FeatureCollection",
"features":
[
{"type":"Feature","properties":{"Name":"","Description":""},"geometry":{"type":"Point","coordinates":[0.0,0.0]}},
{"type":"Feature","properties":{"Name":"1","Description":""},"geometry":{"type":"Point","coordinates":[11.50728,3.87471,0.0]}},
]
};
// vector layer
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geoData)
}),
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.2)'
})
})
});
I've hacked together an example here http://jsfiddle.net/dxt95yt6/1/ that shows it not working but I can't figure out where this differs from the original tutorials.
Given style object is not correct for points and therefore features just don't show up. Try:
style: new ol.style.Style({
image: new ol.style.Circle({
radius: 8,
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.2)'
})
})
})
Please note, in original code, there's another problem, too. Coordinates have to be transformed to EPSG:3857:
features: (new ol.format.GeoJSON()).readFeatures(
geoData,
{featureProjection: ol.proj.get('EPSG:3857')}
)
http://jsfiddle.net/zqx6644q/8/
Its always helpful to validate your geojson before using it. I can recommend geojsonlint which has alos an api to make sure your using a correct geojson.

Unable to draw polline on the map in openlayer3 using direction service

I am trying to add direction service to the map
1:I need to display the map
2:once i get the response from the server or invoke the method only then i should draw the poly line i am trying to do it as shown below
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<!-- <link rel="stylesheet" href="http://openlayers.org/en/v3.2.1/css/ol.css" type="text/css">-->
</head>
<body>
<div id="map" class="map"></div>
<link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>
<script>
var map;
var vectorLayer;
var extentToZoom;
var geojsonObject;
/* function addGeoObject(){
geojsonObject ={"status":200,"hint_data":{"locations":["1DYUCf____89vE8AWwAAANkCAAAAAAAAcAAAAG_vKABaqAAATqcUAIO1MgYAAAEB","1DYUCf____89vE8AEAAAAHAAAADZAgAAAAAAAG_vKABaqAAAtZkUAPGvMgYBAAEB"],"checksum":4294707914},"route_name":["T3 Arrival Drive","T3 Arrival Drive"],"status_message":"Found route between points","route_geometry":"{srqAewyieEzrExuAtDhA","via_indices":[0,2],"route_instructions":[["10","T3 Arrival Drive",418,0,2,"418m","S",202,1,"N",22],["15","",0,2,0,"0m","N",0,"N",0]],"via_points":[[1.35355,103.986563],[1.350069,103.985137]],"found_alternative":false,"route_summary":{"total_distance":418,"total_time":65,"end_point":"T3 Arrival Drive","start_point":"T3 Arrival Drive"}}
//console.log(geojsonObject.coordinates);
}*/
function drawPolyline(geoObject){
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
}),
'LineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 3
})
}),
'MultiLineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 1
})
}),
'MultiPoint': new ol.style.Style({
image: image
}),
'MultiPolygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'yellow',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 0, 0.1)'
})
}),
'Polygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
lineDash: [4],
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}),
'GeometryCollection': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'magenta',
width: 2
}),
fill: new ol.style.Fill({
color: 'magenta'
}),
image: new ol.style.Circle({
radius: 10,
fill: null,
stroke: new ol.style.Stroke({
color: 'magenta'
})
})
}),
'Circle': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.2)'
})
})
};
var styleFunction = function(feature, resolution) {
return styles[feature.getGeometry().getType()];
};
geojsonObject =geoObject;
var routeGeom = new ol.format.Polyline(
{
factor: 1e6
}).readGeometry(geojsonObject.route_geometry, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
});
var routeFeature = new ol.Feature({
geometry:routeGeom
})
extentToZoom = routeGeom.getExtent();
var vectorSource = new ol.source.Vector({
features: [routeFeature]
});
map = new ol.Map({
layers: [
new ol.layer.Vector({
source: vectorSource,
style: styleFunction
})
],
target: 'laneMap'
});
}
function initMap(){
map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
center: ol.proj.fromLonLat([103.986908, 1.353199]),
rotation: 68*Math.PI/180,
zoom: 18
})
});
}
initMap();
geojsonObject ={"status":200,"hint_data":{"locations":["1DYUCf____89vE8AWwAAANkCAAAAAAAAcAAAAG_vKABaqAAATqcUAIO1MgYAAAEB","1DYUCf____89vE8AEAAAAHAAAADZAgAAAAAAAG_vKABaqAAAtZkUAPGvMgYBAAEB"],"checksum":4294707914},"route_name":["T3 Arrival Drive","T3 Arrival Drive"],"status_message":"Found route between points","route_geometry":"{srqAewyieEzrExuAtDhA","via_indices":[0,2],"route_instructions":[["10","T3 Arrival Drive",418,0,2,"418m","S",202,1,"N",22],["15","",0,2,0,"0m","N",0,"N",0]],"via_points":[[1.35355,103.986563],[1.350069,103.985137]],"found_alternative":false,"route_summary":{"total_distance":418,"total_time":65,"end_point":"T3 Arrival Drive","start_point":"T3 Arrival Drive"}};
drawPolyline(geojsonObject);
/* var geoobject2={"status":200,"hint_data":{"locations":["UiQkCf____-ljiMAEAAAABgAAAAAAAAAAAAAAP____-jqAAAt5gUAG2wMgYAAAEB","c8gaCf____8AAAAAMgAAALAAAAAAAAAAHQEAAOviEAajqAAAdqQUABy3MgYAAAEB"],"checksum":4089551480},"route_name":["East Coast Parkway (ECP)",""],"status_message":"Found route between points","route_geometry":"mjkqAyewieEsHuB_m#qWoYwJuDoDoAqBoFaJkCsD}H_Hai#{Pw`#iM","via_indices":[0,10],"route_instructions":[["10","East Coast Parkway (ECP)",18,0,2,"18m","N",21,1,"S",201],["1","",308,1,24,"307m","NE",28,1,"SW",208],["1","",65,9,5,"65m","NE",23,1,"SW",203],["15","",0,10,0,"0m","N",0,"N",0]],"via_points":[[1.349815,103.985261],[1.352822,103.986972]],"found_alternative":false,"route_summary":{"total_distance":391,"total_time":29,"end_point":"","start_point":"East Coast Parkway (ECP)"}};
drawPolyline(geoobject2);*/
initMap();
map.getView().fit(extentToZoom,map.getSize())
</script>
</body>
</html>
In the above code initMap method will draw the plain map
once i invoke the drawPolyline method it should show the plot (this is because i will get the data from the zmq once i get the data i should plot it )
I tried for a long time doing it please help by posting the correct code to accomplish it or suggest a way to do it
Assuming your routing service responds to a simple AJAX GET request, you can save yourself a lot of effort using OpenLayers's built-in layer loading. Something like
function drawPolyline(url) {
map.addLayer(new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.Polyline(),
url: url
}),
style: styleFunction
}));
}
The url argument in the above function is the url you use to get the track from your routing service.

OpenLayers3 - Style each Feature individually

I am adding features to a map by reading their WKT-String:
var feature = wkt.readFeature(entity.WellKnownText);
feature.bxObject = entity;
src.addFeature(feature);
Each feature has a bxObject-Property, and this Property contains the "radius"-Property.
I style the layer, to which the features are added like so:
var layer = new ol.layer.Vector({
source: src,
style: new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
stroke: new ol.style.Stroke({
color: 'blue',
width: 1
}),
fill: new ol.style.Fill({ color: [0, 0, 255, 0.1] })
})
})
});
I want the radius-Property of the style to be dynamic. What I did and works as a workaround is the following:
var layer = new ol.layer.Vector({
source: src,
style: function (feature, resolution) {
return [
new ol.style.Style({
image: new ol.style.Circle({
radius: feature.bxObject.radius || 6,
stroke: new ol.style.Stroke({
color: 'blue',
width: 1
}),
fill: new ol.style.Fill({ color: [0, 0, 255, 0.1] })
})
})
];
}
});
But this creates a new style for each feature... I potentially draw 100s of features and I even have the subjective opinion, that it slows everything down. Is this really the way it is done?
I found this stackoverflow post. But I had no luck trying to interpolate with "${...}". I guess this is an openLayers 2 feature:
var layer = new ol.layer.Vector({
source: src,
style: new ol.style.Style({
image: new ol.style.Circle({
radius: "${bxObject.radius}",
stroke: new ol.style.Stroke({
color: 'blue',
width: 1
}),
fill: new ol.style.Fill({ color: [0, 0, 255, 0.1] })
})
})
});
Yes this is really the way, but you should keep a style cache and re-use when possible. See for instance: http://openlayers.org/en/v3.10.1/examples/kml-earthquakes.html

Resources