Azure Maps with OSM / WMS / other layers in OpenLayers - javascript

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

Related

Add EMODnet Bathymetry layer on the map

I have been testing OpenLayers and got already some layers working. Now I would like to add sea depths layer on the map. However following their example does not show any layers. Am I doing something wrong?
I have successfully added satellite layer using this code:
var satelliteLayer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
maxZoom: 19
})
});
After that I am just performing this map.addLayer(satelliteLayer);
Following EMODnet Bathymetry example, I have added this one:
var seaDepthLayer = new ol.layer.Image({
extent: [-36, 25, 43, 85],
source: new ol.source.ImageWMS({
url: 'https://ows.emodnet-bathymetry.eu/wms',
// refer to the section layer name to find the name of the layer
params: { 'LAYERS': 'mean_atlas_land' }
})
});
Adding their layer in addition to others does not produce any change in my existing maps:
map.addLayer(vectorLayer);
map.addLayer(seaDepthLayer);
map.addLayer(nauticLayer);
https://portal.emodnet-bathymetry.eu/services/

Get adress origin and destination in mapbox gl directions

I'm using the mapbox gl directions from mapbox, which is used in the example of the mapbox documentation.
However, I can't get the values of address enter by the user .
I need the address selected by the user. Thanks!
Here's my code:
<script>
mapboxgl.accessToken = 'MY TOKEN ACCESS';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-79.4512, 43.6568],
zoom: 13
});
map.addControl(
new MapboxDirections({
accessToken: mapboxgl.accessToken
}),
'top-left'
);
</script>
// Docs for route event is here:
// https://github.com/mapbox/mapbox-gl-directions/blob/master/API.md#on`enter code here`
directions.on('route', e => {
// routes is an array of route objects as documented here:
// https://docs.mapbox.com/api/navigation/#route-object:
let routes = e.route
routes.map(r => r.legs[0].steps[0].name)//get the origin
tail=routes.map(r => r.legs[0].steps.length)//get length of instructions
routes.map(r => r.legs[0].steps[tail-1].name)//get destination
});
The mapbox-gl-directions plugin provides getOrigin and getDestination methods for retrieving the origin and destination of the current route, respectively.

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

Using Tiled Google Map With OpenLayers 3

How can I use google map with OpenLayers 3?
I want to migrate from OpenLayers 2 to 3.
here is an example:
google map integration with OpenLayers example
but using this method needs to change the old HTML code (two element needs, 'gmap' and 'olmap' that mentioned in the example).
Google Maps is officially not supported by ol3, but my question is:
"How can I use Google Maps Tile Service in my project like a MapServer, without needing to add google API reference (for optimizing purposes) to the scripts tag?"
Here is my old code that works correctly with OpenLayers 2:
var map = new OpenLayers.Map("map_canvas", {
controls: [
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.ScaleLine(),
new OpenLayers.Control.MousePosition(),
new OpenLayers.Control.OverviewMap()
],
units: "m",
numZoomLevels: 21
});
var gmap = new OpenLayers.Layer.Google(
{ type: google.maps.MapTypeId.ROADMAP, numZoomLevels: 21}
);
map.addLayers([gmap]);
and html code:
<div id="map_canvas">
</div>
appreciate any help.
I found the solution:
JsFiddle
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
url: 'http://mt{0-3}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
attributions: [
new ol.Attribution({ html: '© Google' }),
new ol.Attribution({ html: 'Terms of Use.' })
]
})
})
],
view: new ol.View({
center: ol.proj.transform(
[-110, 45], 'EPSG:4326', 'EPSG:3857'),
zoom: 3
})
});
html, body, #map {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
<link href="http://openlayers.org/en/master/css/ol.css" rel="stylesheet"/>
<script src="http://openlayers.org/en/master/build/ol.js"></script>
<div id="map"></div>
but I'm not sure that this code is in contrast with the Google Terms of Use or not.

Having Javascript talk to Grails for KML

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.

Categories

Resources