OpenLayers with map starting in Australia - javascript

I'm very new to OpenLayers and I'm trying to show a map on my home page, which shows only Australia, and then later add some points on the map. The important thing right now, is to just open the map to Australia.
I'm using the example found on OpenLayers home page, with:
var map = new OpenLayers.Map('map');
var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic'} );
....
I'm guessing that I have to pass something to the constructor to have it display only a specific region?
Thanks,
Sam

Found this on another stackoverflow question:
var bounds = new OpenLayers.Bounds(-125, 25, -65, 50);
var map = new OpenLayers.Map('map', {restrictedExtent: bounds });

Open Layers uses projection to accommodate a 2D map of a 3D world. Projection is a mathematical way of saying that on a 3D sphere (the world) the coordinates x,y are actually x,y somewhere else on a 2D map. In openlayers this involves changing the view, you can use the fromLonLat() method. More information on projection here: https://openlayers.org/en/latest/doc/faq.html
mapOfAustralia = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: targetElement,
controls: ol.control.defaults({
attributionOptions: {
collapsible: false
}
}),
view: new ol.View({
center: ol.proj.fromLonLat([133.7751, -23.2744]),
zoom: 4
})
});

Related

Map crashes when I zoom to an extent that is too far east

I've got a map with a button that zooms to the extent of a feature. It works fine most of the time but when the extent is too far east the entire map dissapears.
This is what I've got in javascript:
function initMap() {
var view = new ol.View({
center: endpoint,
zoom: 4,
maxZoom: 16,
});
map = new ol.Map({
target: 'map',
layers:[],
view: view
});
map.addControl(zoomToExtentControl);
};
zoomToExtentControl = new ol.control.ZoomToExtent({
extent: [-1013450.0281739295, 3594671.9021477713, 6578887.117336057, 10110775.689402476],
className: 'custom-zoom-extent',
label: 'Z'
});
and later in another function:
let xMinMax = ol.proj.fromLonLat([xMin, xMax]);
let yMinMax = ol.proj.fromLonLat([yMin, yMax]);
let padding = 1.06;
zoomToExtentControl.extent = [(xMinMax[0] * padding), (yMinMax[0] * (padding-0.02)), (xMinMax[1] * padding), (yMinMax[1] * padding)];
Why does the map crash when the extent is in the east but work fine when its not? How can I fix this?
I don't understand the xMinMax/yMinMax calculation, ol.proj.fromLonLat input is a coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. It seems you are using two longitudes or two latitudes (I read two x and two y).

OpenLayers adding circle feature with same vectorSource increases opacity of all

Background
Specs
OpenLayers 4.4.1
OSM
I'm fairly new to OpenLayers and have never used vectors before (primarily because I found out that I was using OpenLayers version 1, and had to relearn everything).
My application adds circles to a map relating to a position with a specific radius indicating position accuracy.
In its operation, multiple circles are added to the map at different times.
This is my code for loading the map:
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'mapdiv',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
//center: [0, 0],
zoom: 16
})
});
//this is where all map 'features' (circles) are stored
var vectorSource = new ol.source.Vector({
projection: 'EPSG:4326'
});
As you can see, I load the 'vector source' right after the map as I understood that it holds all 'vectors' which are displayed on the map so long as you specify it as the 'source'.
This is the code I use to generate the circle (source) (I tweaked it at getPointResolution because the OP made a mistake):
//code from https://stackoverflow.com/a/28299599
function addCircle(map, vectorSource, radius) {
var view = map.getView();
var projection = view.getProjection();
var resolutionAtEquator = view.getResolution();
var center = view.getCenter();
var pointResolution = ol.proj.getPointResolution(projection, resolutionAtEquator, center);
var resolutionFactor = resolutionAtEquator/pointResolution;
var radius = (radius / ol.proj.METERS_PER_UNIT.m) * resolutionFactor;
var circle = new ol.geom.Circle(center, radius);
var circleFeature = new ol.Feature(circle);
// vector layer
vectorSource.addFeature(circleFeature);
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
}
Problem
Loading one circle goes normally, adds a blue stroked, opaque circle at the specified location with specified radius.
Loading a second circle appears more opaque than the last. Moving the map to the previous circle, it is also more opaque.
With each added circle, the apparent opacity increases for all displayed circles.
Running vectorLayer.getOpacity() in every circle generation results in 1, when clearly the circle is translucent, becoming increasingly opaque with every new circle.
Summary
Looking around, it appears that often it is the case that the developer is reloading the same circle over and over until many are stacked on top of one another. It almost seems like this is the case for me too, except I've triple-checked that I'm only running addCircle() once and the circle is in a different position than the last.
Is it possible that OpenLayers is redrawing all previous circles with every new circle?
Maybe this isn't related to getOpacity but has to do with the color as an rgba() combination...
Question
I want every circle to remain the same after drawing new circles. The default opacity and color is fine.
Am I doing something wrong?
Here's a fiddle as an example - https://jsfiddle.net/f5zrLt20/5/
Define the layer when defining the vectorSource:
var layer = null;
//this is where all map 'features' (circles) are stored
var vectorSource = new ol.source.Vector({
projection: 'EPSG:4326'
});
And check if it exists on creating a new circle:
// If layer is not yet set, create new layer and add it to map
if (!layer) {
vectorSource.addFeature(circleFeature);
layer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(layer);
}
//Otherwise, just add feature to the source
else {
layer.getSource().addFeature(circleFeature);
}

Openlayers-3 Raster Layer not Changing when Sources Changed

My server is statically serving several different PNG images of the same object, each taken with a different spectral filter (for example, just a red channel or just a blue channel). I'd like to show a slippy, false-colored map of that object. I do so by creating three separate images sources like so:
extent = [0, 0, ncols, nrows];
pixelProjection = new ol.proj.Projection({
code: 'some-image',
units: 'pixels',
extent: extent
});
rsource = new ol.source.ImageStatic({
url: "static/imgs/band_1.png",
projection: pixelProjection,
imageExtent: extent
});
gsource = new ol.source.ImageStatic({
url: "static/imgs/band_2.png",
projection: pixelProjection,
imageExtent: extent
});
bsource = new ol.source.ImageStatic({
url: "static/imgs/band_3.png",
projection: pixelProjection,
imageExtent: extent
});
Next, I use these sources as inputs to a raster source which can compose them:
rgbSources = [rsource, gsource, bsource];
raster = new ol.source.Raster({
sources: rgbSources,
operation: function(bands, data) {
var rband = bands[0];
var gband = bands[1];
var bband = bands[2];
var composed = [
rband[0],
gband[0],
bband[0],
255
];
return composed;
}
});
I then create a layer that uses this raster as its source:
colorLayer = new ol.layer.Image({
source: raster
});
Lastly, I can create a map and add my raster layer to the map:
var map = new ol.Map({
target: 'map',
view: new ol.View({
center:ol.extent.getCenter(extent),
projection: pixelProjection,
zoom: 1.5
})
});
map.addLayer(colorLayer);
So far so good! This displays a colorized version of the image as expected. The problem arises when the user triggers a change to a color channel by inputting a new channel index to pull from. I handle a blue channel change like this:
var index = 4; // actually gets passed in from user
bsource = new ol.source.ImageStatic({
url: "static/imgs/band_" + index + ".png",
projection: pixelProjection,
imageExtent: extent
});
rgbSources[2] = bsource; // this was in global scope from before
raster.sources = rgbSources; // as was this
Expected behavior is that the map would immediately change colors, or at least it would change when I zoom in or pan but neither of those things happens. I am unable to get the new colors to appear at all. Am I updating the wrong thing? Perhaps the raster.sources field has an associated setter function that I am unable to find?
Found a solution! It looks like setting a raster's source directly is not allowed, but setting a layer's source is. So unfortunately, I have to create a new raster object (new source entirely), but at least I don't need a new layer:
raster = new ol.source.Raster({
sources: rgbSources,
operation: composeBands
});
colorLayer.setSource(raster);
Accepting my own answer but willing to accept someone else's solution if it means I don't need to create a new source.

Spherical Mercator Lat/Lon from OpenLayers, want EPSG:4326 format

I am trying to get the EPSG:4236 format of longitude and latitude from OpenLayer, however I spent several hours trying to figure this out and I really don't get what I am doing wrong. I keep getting the spherical mercator format.
For setup I have the following:
var map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
This is my center of the map:
var lonLatCenter = new OpenLayers.LonLat( -73.0, 40.5 )
.transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
var zoom=14;
For click event I have the following code:
map.events.register("click", map, function(e) {
var position = map.getLonLatFromPixel(e.xy);
alert(JSON.stringify(position));
});
I get the following result when clicking on JFK airport in New York City:
{"lon":-8215245.2836805,"lat":4960351.5608374}
I have been reading information here but it seems to only show how to transform from EPSG:4326 to spherical mercator. Help would be appreciated and the link below is to the documentation :
http://docs.openlayers.org/library/spherical_mercator.html
Click event on map object return coordinates using map projection (shperical mercator).
You need to transform them to lat lon, like this
map.events.register("click", map, function(e) {
var position = map.getLonLatFromPixel(e.xy);
position.transform(map.getProjectionObject(), new OpenLayers.Projection('EPSG:4326'));
alert(JSON.stringify(position));
});

coordinates returned are not correct

I'm using OpenLayers3 with OSM as a background map. I'm retrieving coordinates when clicking on the map. However, for some reason I do not understand, the coordinates returned differ from what they should be.
The crs is EPSG:3857 and the coordinates returned are for example:
[149320862354.13303, 7149613.877682245]
But they rather should look like this:
[1347655.049747, 7147342.608955]
I do not know why they are returned like this. I did not change anything in my code or configuration.
map.on('singleclick', function (e) {
var coordinates = map.getEventCoordinate(e.originalEvent);
console.log(coordinates);
}
Any ideas what is causing this?
Edit:
I've logged the map object to console:
projection_: ol.proj.EPSG3857_
revision_: 0
values_: Object
center: Array[2]
0: 149320863424.25146
1: 7177589.830034621
length: 2
__proto__: Array[0]
resolution: 152.8740565703525
rotation: 0
As you can see the coordinates of the center (especially center[0]) are wrong. I guess this issue may be caused by creating the map.
var map = new ol.Map({
layers: [
gnMap.getLayersFromConfig() //MapQuest, OSM, Bing
],
renderer: 'canvas',
view: new ol.View({
center: [0, 0],
projection: 'EPSG:3857',
zoom: 2
})
});
But I can't figure out why those are either created or returned wrong.

Categories