Having Javascript talk to Grails for KML - javascript

I have a controller making a rest call to a web service. It responds with a KML file and then I need to take the response and send it to open layers. I get how to make the call from the controller to the web service, but how do I then use that in a .js file?

Adapting the openlayers/KML example slightly, where "grails URL" is the URL to your controller/action which returns some KML in the response:
var map = new OpenLayers.Map({
div: "map",
layers: [
new OpenLayers.Layer.WMS(
"WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0",
{layers: "basic"}
),
new OpenLayers.Layer.Vector("KML", {
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: **<grails URL>**
format: new OpenLayers.Format.KML({
extractStyles: true,
extractAttributes: true,
maxDepth: 2
})
})
})
],
center: new OpenLayers.LonLat(-112.169, 36.099),
zoom: 11
});
Obviously, the other configuration (center, zoom etc) you will need to adapt to your own needs.

Related

Openlayers display Points from Geodjango REST API endpoint

I am trying to display points on an OSM map using Openlayers and (Geo)Django. The points should be provided by a REST API endpoint which I want to query from within the openlayers javascript.
The JS part looks like this:
<div id="map" class="map shadow m-auto"></div>
<script type="text/javascript">
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: "http://localhost:8000/api/sites"
})
}) ,
new ol.layer.Tile({
source: new ol.source.OSM(),
})
],
view: new ol.View({
center: ol.proj.fromLonLat([8,48]),
zoom: 10
})
});
</script>
The API endpoint is just serializing a django queryset and therefore returns the following:
[
{
"sid":13,
"site_name":"Burgsteig",
"site_notes":"Reuter.2003",
"municipality":1047,
"geom":{
"type":"Point",
"coordinates":[
8.779644092464917,
48.00504767358004
]
}
},
{
"sid":14,
"site_name":"Brederis, \"Weitried\"",
"site_notes":"Hagn2002",
"municipality":16180,
"geom":{
"type":"Point",
"coordinates":[
9.628734475883569,
47.2756455228491
]
}
},
{
"sid":15,
"site_name":"Burgweinting, \"Villa\"/\"Mühlfeld\"",
"site_notes":"Zintl2012, Zintl2013",
"municipality":2767,
"geom":{
"type":"Point",
"coordinates":[
12.11373087937611,
49.01308089544727
]
}
}
]
It is just a basic API endpoint by django-rest-framework and as far as i know returns a pretty standard geoJSON format dataset. However, when running this i get an "Uncaught Error: Unsupported GeoJSON type: undefined". The basemap is displaying, it is just something wrong with that geojson. As far as I understand, the API is not returning GeoJSON as in ol.format.GeoJSON() but something else instead. So how do I process this thing to be displayed on my map?

Azure Maps with OSM / WMS / other layers in OpenLayers

I am trying to add an azure maps layer to my openlayers project. I can make a basic map work using this third party plugin and example with my azure maps key. However when I try to add an additional layer such as OSM or a WMS layer from Geoserver it throws an error in the console: "Uncaught TypeError: ol.source.OSM is not a constructor". I have many different layer types (OSM, WMS, XYZ) that I would like to add alongisde the Azure but I cannot get any of these to work, they are all throwing similar error.
Any ideas how to add other layers alongside Azure maps in Openlayers?
Relevant code snippet:
<!-- Add reference to the Azure Maps OpenLayers plugin.-->
<script src="./js/azure-maps-openlayers.js"></script>
<script type='text/javascript'>
var map;
function GetMap() {
//Add authentication details for connecting to Azure Maps.
var authOptions = {
authType: 'subscriptionKey',
subscriptionKey: 'aaaaaaaabbbbbbbbccccccccddddddddd'
};
//Create a map instance.
map = new ol.Map({
target: 'myMap',
layers: [
new ol.layer.Tile({
type: 'base',
visible: true,
source: new ol.source.AzureMaps({
authOptions: authOptions,
tilesetId: 'microsoft.imagery'
})
}),
new ol.layer.Tile({
type: 'overlay',
visible: false,
source: new ol.source.OSM()
})
],
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
}
</script>
I have done some research but I didn't found any scenario or document which suggests how can we integrate OSM layer with the Azure Maps in OpenLayers.
If you check this Azure Maps Class, you will understand why are you getting the error.
Namespace: ol.source
A tile source that connects to the Azure Maps Render V2 services.
Contstructor
AzureMaps(options?: AzureMapsTileSourceOptions)
But if you want to integrate WSM layer with Azure Maps then you can achieve it by adding the OGC web-mapping service with Azure Maps as shown in the following code snippet.
//Initialize a map instance.
var map = new atlas.Map('map', {
view: "Auto",
//Add your Azure Maps subscription client ID to the map SDK. Get an Azure Maps client ID at https://azure.com/maps
authOptions: {
authType: "anonymous",
clientId: "04ec075f-3827-4aed-9975-d56301a2d663", //Your AAD client id for accessing your Azure Maps account
getToken: function (resolve, reject, map) {
//URL to your authentication service that retrieves an Azure Active Directory Token.
var tokenServiceUrl = "https://azuremapscodesamples.azurewebsites.net/Common/TokenService.ashx";
fetch(tokenServiceUrl).then(r => r.text()).then(token => resolve(token));
}
}
});
//Wait until the map resources are ready.
map.events.add('ready', function () {
map.layers.add(new atlas.layer.TileLayer({
tileUrl: 'https://mrdata.usgs.gov/services/gscworld?FORMAT=image/png&HEIGHT=1024&LAYERS=geology&REQUEST=GetMap&STYLES=default&TILED=true&TRANSPARENT=true&WIDTH=1024&VERSION=1.3.0&SERVICE=WMS&CRS=EPSG:3857&BBOX={bbox-epsg-3857}',
tileSize: 1024
}), 'transit');
});
For more information check this Add a tile layer Microsoft document.
If you want to work on Azure Maps with OpenLayers, then I would suggest you to Azure Maps OpenLayers plugin. OpenLayers plugin makes it easy to overlay tile layers from the Azure Maps tile services. You can only use the Azure Maps tile layers as shown in the example below.
//Create a map instance.
map = new ol.Map({
target: 'myMap',
layers: [
new ol.layer.Tile({
source: new ol.source.AzureMaps({
authOptions: authOptions,
tilesetId: 'microsoft.imagery'
})
}),
new ol.layer.Tile({
source: new ol.source.AzureMaps({
authOptions: authOptions,
tilesetId: 'microsoft.base.road'
})
})
],
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
I would strongly suggest to read this Azure Maps OpenLayers plugin document completely and also check this Azure-Samples/AzureMapsCodeSamples GitHub code sample for more information.
Ok, I've managed to get this to work via the following code. It's actually posted on the Azure Maps Openlayers plugin page right at the bottom - "Alternative Option for OpenLayers". Ironically the plugin is not needed at all in order to get it to work - you just reference the Azure Maps layer as an ol.source.XYZ layer. Obviously you can change the visibility options of both layers in order to visualise them - or add them into a layer switcher.
var map;
function GetMap() {
var subscriptionKey = 'my_subscription_key_goes_here';
var tilesetId = 'microsoft.imagery';
var language = 'EN';
var view = new ol.View({
center: [0, 0],
zoom: 2
});
//Create a map instance.
map = new ol.Map({
target: 'myMap',
layers: [
new ol.layer.Tile({
type: 'base',
visible: true,
source: new ol.source.XYZ({
url: `https://atlas.microsoft.com/map/tile?subscription-key=${subscriptionKey}&api-version=2.0&tilesetId=${tilesetId}&zoom={z}&x={x}&y={y}&tileSize=256&language=${language}`,
attributions: `© ${new Date().getFullYear()} TomTom, Microsoft`
})
}),
new ol.layer.Tile({
type: 'overlay',
visible: true,
source: new ol.source.OSM()
})
],
view: view
});
}

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

OpenLayers getFeatureInfo popup generates this.size is null

I am trying to create OpenLayers with popup feature info. I got the code from OpenLayers examples and only modified url to my local geoserver. The map is displaying, when i click on a feature the request is sent but the response is empty and firebug shows error "this.size is null". When i run the request url separately feature info is generated.
Here is the code:
var map, info;
function load() {
map = new OpenLayers.Map({
div: "map",
maxExtent: new OpenLayers.Bounds(20.163,53.228,20.208,53.257)
//maxExtent: new OpenLayers.Bounds(143.834,-43.648,148.479,-39.573)
//maxExtent: new OpenLayers.Bounds(19,90,19,90)
});
var punkty_zdjecia = new OpenLayers.Layer.WMS("Punkty Zdjecia",
"http://localhost:6060/geoserver/wms",
{'layers': 'cite:ulice2', transparent: false, format: 'image/gif'},
{isBaseLayer: true}
);
map.addLayers([punkty_zdjecia]);
info = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost:6060/geoserver/wms',
title: 'Test url',
queryVisible: true,
eventListeners: {
getfeatureinfo: function(event) {
map.addPopup(new OpenLayers.Popup.FramedCloud(
"chicken",
map.getLonLatFromPixel(event.xy),
new OpenLayers.Size(200,200),
event.text,
null,
true
));
}
}
});
map.addControl(info);
info.activate();
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToMaxExtent();
}
I am using OpenLayers 2.11 and Firefox browser

Categories

Resources