I´m trying to hide/show my own kml files (polygons) depending on zoom levels in OpenLayers - when reached certain zoom level one layer should hide and another show. So far I found this solution (How to load layers depending on zoom level?), but it doesn´t seem to be working in my case. I´m relatively new to javascript and I don´t know if I´m using this right, I also made some changes to the example:
map.events.register("zoomend", map, zoomChanged); //inserted in function init()
function zoomChanged()
{
if (map.getZoom() == 18)
{
kml1.setVisibility (true);
kml2.setVisibility (false);
}
else if (map.getZoom() == 19)
{
kml1.setVisibility (false);
kml2.setVisibility (true);
}
}
I also tried another solution to hide kml1, but in this case my layer isn´t drawn. The LayerSwitcher works - the layer is unselectable in defined zoom levels, but nothing is visible when zoomed out (when layer is already selectable):
var kml1 = new OpenLayers.Layer.Vector("prehled",
{minScale: 1000,}, //1:1000
{
projection: map.displayProjection,
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: "kml/zahrada.kml",
format: new OpenLayers.Format.KML({
extractStyles: true,
extractAttributes: true,
})
})
});
map.addLayer(kml1);
Thanks for any response and advice on this.
Try:
var kml1 = new OpenLayers.Layer.Vector("prehled", {
minResolution: map.getResolutionForZoom(18), // or the desired maximum zoom
projection: map.displayProjection,
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: "kml/zahrada.kml",
format: new OpenLayers.Format.KML({
extractStyles: true,
extractAttributes: true
})
})
});
map.addLayer(kml1);
```
Related
this is my layer and i have assigned it to a button, but the zoom is not working when I click the layer button. i tried adding the zoom inside the layer but its not working.
rainfall1 = new ol.layer.Vector({
//title: 'CA_DEVELOPMENT_PLAN',
// extent: [-180, -90, -180, 90],
visible:false,
source: new ol.source.Vector({
url:"./data/village.geojson",
zoom: 12,
format: new ol.format.GeoJSON()
}),
style:function(feature) {
labelStyle.getText().setText(feature.getProperties().CA_NAME);
return style1;
},
declutter: true,
});
document.getElementById("lyr").onclick = function() {
layer1.setVisible(!rainfall1.getVisible());
};
var bindLayerButtonToggle = function (lyr, layer) {
document.getElementById(lyr).onclick = function() {
layer.setVisible(!layer.getVisible());
};
}
bindLayerButtonToggle("lyr", rainfall1);
setVisible will not zoom to a layer, it just turns it on or off.
Instead, you would have to update the view extent, and match it with the layer extent
map.getView().fit(rainfall1.getSource().getExtent());
#JGH's answer might work in some cases but if this is the first time the layer is made visible the source will not be loaded, so if there are no features you will need to wait for it to load before zooming.
if (rainfall1.getSource().getFeatures().length > 0) {
map.getView().fit(rainfall1.getSource().getExtent());
} else {
rainfall1.getSource().once('featuresloadend', function() [
map.getView().fit(rainfall1.getSource().getExtent());
});
}
I want to combine two layers for my map, ortophoto map and on top of that, polygons showing parcel boundaries. For ortophoto I have available WMTS and for polygons WMS.
Projection I need to use is EPSG:3765. The problem is, when I combine these two layers, they don't match at all, polygons are on a completely wrong places.
Initially I tried to implement similar thing in a Leaflet but with using older WMS source for ortophoto map and it worked fine, but since now I wanted to use WMTS, I switched to OpenLayers and cannot get it to work properly. I guess the main problem is projection.
I am completely new to this area so I apologize in advanced if there is some obvious error I did.
Here is my code from main.js, I set projection extent based on info from epsg site, resolution and origin were set based on data found in getCapabilities response:
const projName = 'EPSG:3765';
proj4.defs(projName,"+proj=tmerc +lat_0=0 +lon_0=16.5 +k=0.9999 +x_0=500000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs +type=crs");
register(proj4);
const projection = getProjection(projName);
projection.setExtent([208311.05, 4608969.52,744179.92, 5161549.72]);
const scaleDenominators = [5000000.0,2500000.0,1000000.0,500000.0,250000.0,100000.0,50000.0,25000.0,10000.0,5000.0,2500.0,1000.0,500.0]; //from getCapabilities
const resolutions = new Array(13);
const matrixIds = new Array(13);
for (let z = 0; z < resolutions.length; ++z) {
resolutions[z] = 0.00028 * scaleDenominators[z];
matrixIds[z] = z;
}
let tileGrid = new WMTSTileGrid({
origin: [-203224.0, 5429184.0], //from getCapabilities topLeftCorner
sizes: [[4,3],[8,6],[20,15],[39,30],[78,60],[194,149],[387,298],[774,596],[1934,1489],[3868,2977],[7735,5953],[19338,14881],[38675,29762]], //from getCapabilities
resolutions: resolutions,
matrixIds: matrixIds,
tileSize: [256, 256],
});
const map = new Map({
layers: [
// main raster
new TileLayer({
opacity: 0.7,
source: new WMTS({
url: 'https://geoportal.dgu.hr/services/auth/orthophoto_2019_2020/wmts?authKey=<key>',
layer: 'DOF5_2019_2020',
matrixSet: 'EPSG3765:256x256',
format: 'image/jpeg',
projection: projection,
tileGrid: tileGrid,
extent: projection.getExtent(),
style: 'default',
wrapX: true,
}),
}),
// layer with parcel boundaries
new TileLayer({
extent: projection.getExtent(),
source: new TileWMS({
url: 'https://www.geohrvatska.hr/viewer/oss/wms',
params: {
'LAYERS': 'oss:DKP_CESTICE',
'format': 'image/png',
'version': '1.1.1',
'crs' : projName,
},
serverType: 'geoserver',
transition: 0,
projection: projection,
}),
}),
],
target: 'map',
view: new View({
projection: projName,
center: [477174.25,4882262.63],
zoom: 1
}),
});
Here is a snipet of getCapabilities response displaying TileMatrixSet used:
<TileMatrixSet>
<ows:Identifier>EPSG3765:256x256</ows:Identifier>
<ows:SupportedCRS>urn:ogc:def:crs:EPSG::3765</ows:SupportedCRS>
<TileMatrix>
<ows:Identifier>0</ows:Identifier>
<ScaleDenominator>5000000.0</ScaleDenominator>
<TopLeftCorner>-203224.0 5429184.0</TopLeftCorner>
<TileWidth>256</TileWidth>
<TileHeight>256</TileHeight>
<MatrixWidth>4</MatrixWidth>
<MatrixHeight>3</MatrixHeight>
</TileMatrix>
<TileMatrix>
<ows:Identifier>1</ows:Identifier>
<ScaleDenominator>2500000.0</ScaleDenominator>
<TopLeftCorner>-203224.0 5429184.0</TopLeftCorner>
<TileWidth>256</TileWidth>
<TileHeight>256</TileHeight>
<MatrixWidth>8</MatrixWidth>
<MatrixHeight>6</MatrixHeight>
</TileMatrix>
result:
result
EDIT
After a comment from Mike, I tried displaying my WMTS on top of OSM. For tileMatrix=4, it is aligned while from tileMatrix=5 it is not. I am uploading pictures for demonstration:
tileMatrix=4
tileMatrix=5
I am trying to add ol3 geocoder control in my project. I have set fix zoom level and it is working in Mozilla and it comes properly with appropriate zoom level but in google chrome it is not working. It takes the location on deep zoom in level. I have to zoom out to check surrounding places.
var geocoder = new Geocoder('nominatim', {
provider: 'google',
key:' AIzaSyClQ0GOW55zhw4PvFh73FyGLHdSd4bJfpM',
lang: 'en',
placeholder: 'Search Location...',
limit: 5,
keepOpen: true,
autoComplete: true,
});
map.addControl(geocoder);
//Listen when an address is chosen
geocoder.on('addresschosen', function(evt){
var
feature = evt.feature,
coord = evt.coordinate,
address_html = feature.get('address_html');
content.innerHTML = '<p>'+address_html+'</p>';
if (coord) {
//alert("if--");
map.getView().setZoom(7);
overlay.setPosition(coord);
} else {
map.getView().setZoom(8);
overlay.setPosition(coord);
}
});
When using the latest version of geocoder (3.0.1) it seems you can set the zoom level within the function. I had the same problem when I switched to new version, but I played around and found that it works perfectly like this:
geocoder.on('addresschosen', function (evt) {
window.setTimeout(function () {
view.setZoom(12);
popup.show(evt.coordinate, evt.address.formatted);
}, 1000);
});
Obviously, use whatever zoom value you like.
I have a web app with a map in it. I've added a nice little custom map control to turn on and off different layers on the map. Currently there are only two layers, and it all works nice and fine in most browsers.
Except for IE8+7. None of the layers are showing on the map when turned on. As far as I can tell the map is loading the kmz/kml files (when preserveViewport is set to false, the map moves to the right location) but they're just not appearing. One layer contains polylines, and the other contains markers. The code I use is below:
function someFunction() {
//code to initialise map etc goes here...
var layers = [];
//Create 1st layer
var exchangeslayer = new google.maps.KmlLayer('http://link.to.file/exchanges.kmz'
suppressInfoWindows: true,
preserveViewport: true
});
layers.push({name: "Exchanges", layer: exchangeslayer});
//Code to create second layer
var nyclayer = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml'
suppressInfoWindows: true,
preserveViewport: false
});
layers.push({name: "NY City Tracks", layer: nyclayer});
addCustomLayerControls(layers);
}
function addCustomLayerControls(layers) {
//there is code here that would generate the divs for the custom map control
var container; //container is a div element created via javascript
for (var i = 0; i < layers.length; i++) {
this.addLayerLabelToContainer(layers[i], container);
}
//some more code
}
function addLayerLabelToContainer(layer, container) {
var map; //Assume I get a reference to the map
//some code here to make pretty labels for the map controls...
var layerLabel; // layerLabel is a div element created via javascript
google.maps.event.addDomListener(layerLabel, 'click', function() {
if(layer.layer.map == null) {
layer.layer.setMap(map);
} else {
layer.layer.setMap(null);
}
});
}
So as it turns out my problem related to CSS. One of my stylesheets was applying max-width: 100% to all img tags. This was playing havok with the map markers/polylines.
Its obvious now that I see it, but when you think the problem is to do with the javascript its not so obvious. As such, I'll leave this answer here for anyone else who makes the same mistake as me.
If you modify addLayerLabelToContainer() like this then it works in IE as expected. Verified it loads KMZ correctly in IE 8 and 9.
function addLayerLabelToContainer(layer, container) {
// var map; //Assume I get a reference to the map
//some code here to make pretty labels for the map controls...
var layerLabel; // layerLabel is a div element created via javascript
if(layer.layer.map == null) {
layer.layer.setMap(map);
} else {
layer.layer.setMap(null);
}
}
Don't need to invoke addDomListener(). Also note the API syntax:
addDomListener(instance:Object, eventName:string, handler:Function)
Also minor fix of syntax errors in someFunction as follows:
function someFunction() {
// var map; //assume map is initialised, I've just removed that code
var layers = [];
// see https://developers.google.com/maps/documentation/javascript/layers
//Create 1st layer
var exchangeslayer = new google.maps.KmlLayer(
'http://kml-samples.googlecode.com/svn/trunk/kml/kmz/simple/big.kmz',
{ suppressInfoWindows: true, preserveViewport: true
});
layers.push( {name: "Exchanges", layer: exchangeslayer} );
// ...
addCustomLayerControls(layers);
}
This is my first time on stackoverflow and working with Openlayers & Google Maps.
I've been browsing different forums & sites, including OpenLayers.org, to solve my issue. I've done searches on a combination of the following: openlayers, google map projections, and spherical mercator... but I have not found a solution.
Problem: The KML data from a web service call (func setDataSource) is shifting as I zoom in and out of the map. My guess is that the projections in my code are wrong or perhaps wrongly placed. I don't have any background on map projections so it is difficult to digest mapping terminology online :-(. Can someone help?
//start here
var options = {
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
units: "m",
numZoomLevels: 18,
maxResolution: 156543.0339,
maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
20037508, 20037508)};
//*map = new OpenLayers.Map('map');
map = new OpenLayers.Map('map', options);
var gphy = new OpenLayers.Layer.Google(
"Google Street",
{'sphericalMercator':true});
// Add the background images via WMS
var bglayer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'}, {'reproject': true});
//map.addLayer(bglayer);
map.addLayers([gphy, bglayer]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToMaxExtent(); //* Zoom all the way out, this command also initalizes the map
OpenLayers.Console.log("initialized");
}
function setDataSource() {
OpenLayers.Console.log("Setting data source to " + OpenLayers.Util.getElement('loc').value);
if (layer != undefined) {map.removeLayer(layer)};
if (selectControl != undefined) {map.removeControl(selectControl)};
// Encode the destination url as a parameter string.
var params = OpenLayers.Util.getParameterString({url:OpenLayers.Util.getElement('loc').value})
// Make the http request to the transformer, with the destination url as a parameter.
layer = new OpenLayers.Layer.GML("KML", transformerURL + params,
{
format: OpenLayers.Format.KML,
formatOptions: {
extractStyles: true,
extractAttributes: true,
maxDepth: 2,
//projection: new OpenLayers.Projection("EPSG:4326"),
}
});
map.addLayer(layer);
Thank you!!!
I figured out the problem. Instead of GML, I tried using Vector instead like this:
layer = new OpenLayers.Layer.Vector("KML", {
projection: map.displayProjection,
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: transformerURL + params,
format: new OpenLayers.Format.KML({
extractStyles: true,
extractAttributes: true
})
})
});
I found the solution in this sundials example: http://openlayers.org/dev/examples/sundials-spherical-mercator.html :-) Hope this helps anyone w/ the same problem.