Snippets

Piotr Szrajber Smart M.App - toggle WMS layer

Created by Piotr Szrajber
/**
* 2017-05-12
*/

var layerAdded = false,
    legendEntryId;

function removeLayer() {
    gsp.legend.find({id : legendEntryId}, function (ret) {
    	ret.legendItems.slice(-1)[0].remove();
    	layerAdded = false;
    });
}

function addLayer() {
    zoomToBBox({x: -179.9999, y: -89.9999 }, { x: 179.9999, y: 89.9999 });
    var wmsUrl = "https://ahocevar.com/geoserver/wms?some-custom-query=1",
       legendDefinition = {
           definitionName: "WMS",
           url: wmsUrl,
           id: "ne:NE1_HR_LC_SR_W_DR",
           name: "Demis Map",
           bbox:  [-180, -90, 180, 09],
           bboxCrs: "EPSG:4326",
           supportedCrses: ["EPSG:4326", "EPSG:3857"],
           omitCrsDetection: true
       };
    
    gsp.legend.add(legendDefinition, function (response) {
        legendEntryId = response.ids[0];
        layerAdded = true;
    }, function (error) {
        console.error(error);
    } );
}

function zoomToBBox (bottomLeftCorner, topRightCorner, callback, errback) {
    // transform sample points to current CRS
    gsp.crs.transform({
        points: [bottomLeftCorner, topRightCorner],
        sourceCrsId: "EPSG:4326",
        targetCrsId: gsp.crs.getCurrent()
    }, function (transformationResult) {
        // get BBOX in form minx, miny, maxx, maxy
        var points = transformationResult.points,
            bbox = [points[0].x, points[0].y, points[1].x, points[1].y];
        gsp.map.zoom({
            bbox: bbox
        });
    });
}

gsp.ui.toolbar.add({
    id: "toggle-layer",
    title: "Toggle layer"
}, function (ret){
    ret.div.onclick = function () {
        if (layerAdded) {
            removeLayer();
        } else {
            addLayer();
        }
    };
});

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.