Using encoded polylines in OpenLayers 3 - javascript

I am having trouble when trying to use encoded polylines in OpenLayers 3. I have an external source providing the encoded strings, but when I try to convert them into a feature and add them to a vector source, I get the following error:
Uncaught TypeError: Cannot read property 'ua' of undefined
Here is the current code I am using:
vectorSource = new ol.source.Vector();
var layers = [
new ol.layer.Tile({
name: "SKL Tile Server",
source: new ol.source.OSM({
url: "https://placeholder/osm/{z}/{x}/{y}.png",
crossOrigin: null
})
}),
new ol.layer.Vector({
name: "polylines",
source: vectorSource
})
];
map = new ol.Map({
layers: layers,
target: 'report_map',
view: new ol.View({
center: ol.proj.transform(
[-118.014670, 45.35724], 'EPSG:4326', 'EPSG:900913'),
zoom: 10
})
})
var addPolylineToMap = function (encoded_line, line_style) {
var line = new ol.format.Polyline().readGeometry({
source: encoded_line,
options: {
dataProjection: ol.proj.get('EPSG:4326'),
featureProjection: ol.proj.get('EPSG:900913')
}
});
line.setStyle(line_style);
vectorSource.addFeature(new ol.Feature(line));
return line;
};
Admittedly, I am quite new to OpenLayers 3--but I have searched extensively and can't seem to find any examples of using encoded polylines in OpenLayers 3.

Try this way:
var addPolylineToMap = function (encoded_line, line_style) {
var format = new ol.format.Polyline({
//factor: 1e6
});
var line = format.readGeometry(encoded_line, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:900913'
});
var feature = new ol.Feature({geometry: line});
feature.setStyle(line_style);
vectorSource.addFeature(feature);
return line;
};

Related

"map.once is not a function error" trying to duplicate OpenLayers example

I am trying to duplicate this OpenLayers 6 example
https://openlayers.org/en/latest/examples/export-map.html
It is to a javascript to download your OpenLayers 6 map
I am using different configuration and haven't been able to get it to work
http://australiamap.ca/export-map/
I get a "map.once is not a function error"
Here is your code (i truncated some part for readability)
window.onload = init;
function init(){
const torontoCenterCoordinate = [-8850000, 5410000]
const map = new ol.Map({
view: new ol.View({
center: torontoCenterCoordinate,
zoom: 10
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map'
})
}
function init2(){
...
}
document.getElementById('export-png').addEventListener('click', function () {
map.once('rendercomplete', function () {
...
});
map.renderSync();
});
You are trying to access variable map which is declare inside function init inside event listener of click. That's possible due to how scope work in JavaScript.
There is a coincidence that map actually resolve to a DOM element (in modern browser if you have an HTML element with id map then browser will save that element into variable map for you)
To fix your problem, you can either:
Move move to global scope so event listener can access it
// outside of init
const map = new ol.Map({
view: new ol.View({
center: torontoCenterCoordinate,
zoom: 10
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map'
})
Move even listener inside init
function init(){
const torontoCenterCoordinate = [-8850000, 5410000]
const map = new ol.Map({
view: new ol.View({
center: torontoCenterCoordinate,
zoom: 10
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map'
})
document.getElementById('export-png').addEventListener('click', function () {
map.once('rendercomplete', function () {
...
});
map.renderSync();
});
}

VectorLayer not showing with OpenLayers

I'm basically trying to reproduce the center example in my own JsFiddle
const geoJSON = {};
const features = new ol.format.GeoJSON().readFeatures(geoJSON);
const vectorSource = new ol.source.Vector({
features: features,
});
const style = new ol.style.Style({});
const vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: style,
});
let olView = new ol.View({
center: ol.proj.fromLonLat([6.6339863, 46.5193823]),
zoom: 4,
});
let olLayers = [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
vectorLayer
];
new ol.Map({
layers: olLayers,
view: olView,
target: 'app',
});
I must be missing somethig obvious, as the vector layer isn't showing in my fiddle.
If you pan down you will see the vector for Switzerland is in the wrong place
If using readFeatures you need to specify the feature projection so the geojson Lon/Lat coordinates are transformed to view projection
const features = new ol.format.GeoJSON().readFeatures(geoJSON, {featureProjection: olView.getProjection()});
https://jsfiddle.net/apowe4gj/

"SecurityError: This operation is insecure" when calling domtoimage.toPng() in OpenLayers example

I am currently working on adding functionality to convert an OpenLayers Map into a png file (The example is here). However, when calling domtoimage.toPng() in the below code, Firefox (Ubuntu version 68.0.2) gives me the error SecurityError: This operation is insecure. I have checked all around and no one else seems to be having this problem with the dom-to-image library, and so I am stuck on how to fix this error. My JavaScript code for the Map is very similar to the code given in the example and is given here:
<script type="text/javascript">
var extent = [0, 0, 3000, 4213];
var projection = new ol.proj.Projection({
code: 'my-image',
units: 'pixels',
extent: extent,
});
var map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.FullScreen()
]),
layers: [
new ol.layer.Image({
source: new ol.source.ImageStatic({
attributions: 'My Image Attributions',
url: "{{record | img_url}}", // Django stuff defined earlier
projection: projection,
imageExtent: extent
})
})
],
target: 'map',
view: new ol.View({
projection: projection,
center: ol.extent.getCenter(extent),
zoom: 2,
maxZoom: 8
})
});
map.addOverlay(new ol.Overlay({
position: [0, 0],
element: document.getElementById('null')
}));
// export options for dom-to-image.
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() {
domtoimage.toPng(map.getTargetElement(), exportOptions)
.then(function(dataURL) {
var link = document.getElementById('image-download');
link.href = dataURL;
link.click();
});
});
map.renderSync();
});
The HTML is effectively the same as in the example and so I believe the problem lies somewhere in here. Perhaps it is something with using a StaticImage in the Map? Or maybe going through the Django framework tampers with it in some unknown way? I am not entirely sure, and any diagnosis/help with fixing this issue would be much appreciated.
I think there should be something like:
new ol.layer.Tile({
name: 'name',
source: new ol.source.TileWMS({
...
crossOrigin: 'anonymous' // <-- Add this to the json.
})
})
Read more:
https://openlayers.org/en/v4.6.5/apidoc/ol.source.ImageWMS.html
https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

How do I trigger an on demand refresh/redraw of ol.Map

I have a function called "LoadMap"
rcisWebMapLoad.prototype.LoadMap = function (param1, param2) {
//Get some vector objects and create layers
var fieldVectorObjs = rcisWebMapVectorObjs.GetFieldVectorObjects(param1, param2);
var objectVectorLines = rcisWebMapVectorObjs.GetLinesVectorObjects(param1, param2, 1);
//Create Map object and add layers then insert into map div
control.map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: layers,
view: new ol.View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 8
})
});
//******* MapServer imagery ***************
var aerial = new ol.layer.Tile({
name: 'Imagery',
source: new ol.source.TileWMS({
url: mapServerPath.ResponseString,
params: { 'LAYERS': 'aerial', 'FORMAT': 'image/png', 'TILED': true },
serverType: 'mapserver'
})
});
control.map.addLayer(aerial);
}
This loads the map great!!
I have my imagery and vector objects on the map...however the problem comes when I want to switch to a different map ie.(Different imagery and vector objects)...
UPDATE:
originally I thought the map was not getting updated but in reality another map get's generated and added right under the original map...How do I reuse or replace the map object that is already there to display another map?
Because I'm using AngularJS and passing the maps parameters through a service I can not just call the page again and get the parameters from the query string as someone suggested to me before.
This seems like something that would be a main function for an online map.
Any help is greatly appreciated
Okay, so I was not able to force an on-demand refresh of the map object for OpenLayers 3.
So what I ended up doing was to destroy the map object and create a new one each time.
so for the example above it would look like this...
For angularJS users you also need to make sure that you create an empty map in your .factory load function (so there is something to destroy initially)...if you're not using angular you would just need to create the map on page load.
function rcisWebMapLoad() {
this.map = new ol.Map({});
}
rcisWebMapLoad.prototype.LoadMap = function (param1, param2) {
//Get some vector objects and create layers
var fieldVectorObjs = rcisWebMapVectorObjs.GetFieldVectorObjects(param1, param2);
var objectVectorLines = rcisWebMapVectorObjs.GetLinesVectorObjects(param1, param2, 1);
var layers = [];
Destroy map object before creating a new one
control.map.setTarget(null);
control.map = null;
//Create Map object and add layers then insert into map div
control.map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: layers,
view: new ol.View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 8
})
});
//******* MapServer imagery ***************
var aerial = new ol.layer.Tile({
name: 'Imagery',
source: new ol.source.TileWMS({
url: mapServerPath.ResponseString,
params: { 'LAYERS': 'aerial', 'FORMAT': 'image/png', 'TILED': true },
serverType: 'mapserver'
})
});
control.map.addLayer(aerial);
}

how can i dynamically update a ol.Features geometry property ( coordinates ) in OpenLayers 3

Im just getting started with OpenLayers 3 and i am trying to dynamically update a Features geometry property with coordinates, obviously there is something that i am missing out because the Feature is not moving. Here is what i god so far:
Socket.IO
socket.on('mapData', function(mapData) {
if (mapisloaded) {
latLon = ol.proj.transform([mapData.lon, mapData.lat], 'EPSG:4326', 'EPSG:3857');
// Initiate latlong object with mapData
if (centerIsRequested) {
//Center map with mapData
};
// Update marker with latlong from mapData
};
});
OpenLayers 3 based on the Vector Icon Example
var latLon = ol.proj.transform([10.904108, 59.788187], 'EPSG:4326', 'EPSG:3857');
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(latLon),
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: 'imgs/lc.png'
}))
});
iconFeature.setStyle(iconStyle);
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var baseLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var view = new ol.View({
center: latLon,
zoom: 18,
});
var map = new ol.Map({
target: 'map-canvas',
layers: [ baseLayer, vectorLayer ],
view: view
});
The changes are obviously not changing, but i know that magic does not exist it was just to put something down to start with.
How wouldi go forward accomplish this simple task? The only thing i want is the icon to update its position on the map when socket.io detects the new mapdata (mapData.lat, mapData.lon).
I have tried to dig into the different objects and read their properties both in the console and in the documentation, and i have searched here on Stackoverflow but sadly without luck. Do i hook into the iconFeature, or do i have to do this another way? Maybe something really easy is built in? Any help is much appreciated.
If you want to move an icon over the map, it's better you use an ol.Overlay for this. You can use marker.setPosition(coord) on each change.
A working fiddle. Click on map to change marker's position.

Categories

Resources