Simple API MapBS

Diese Seite beschreibt wie die Simple API genutzt werden kann. Die Simple API bietet eine JavaScript API für das einfache Einbinden in Webseiten.

Technisch gesehen, ist die SimpleApi eine kleine OpenLayers 3 Anwendung, die Kartendienste WMS und WMTS des Kantons Basel-Stadt bereits verknüpft hat. Vordefinierte Methoden, wie unten beschrieben können über das "mapbs"-Objekt genutzt und individuell erweitert werden. Beispiele werden im Folgenden aufgeführt.

Grundlagen

Um die API nutzen zu können, einfach folgenden Code hinzufügen:


<meta charset="utf-8">
<link href="https://map.geo.bs.ch/api.css" rel="stylesheet">
<script src="https://map.geo.bs.ch/api.js?version=2"></script>
<script>
window.onload = function() {
    // add the code here
};
</script>
            

Um ein Kartenelement in der Karte einzubinden muss ein div Elementmit einer bestimmten id dort hinzugefügt werden, wo die Karte erscheinen soll:

<div id='map1' style='width:700px;height:400px;'></div>

Ein einfacher Kartenausschnitt

    const map = new mapbs.Map({
        div: 'map1', // id of the div element to put the map in
        zoom: 4,    
        center: [2611484, 1267592]
    });
                        

Ein Kartenausschnitt mit einem Marker-Punkt in der Mitte

const map = new mapbs.Map({
    div: 'map2',
    zoom: 4,
    backgroundLayers: ['Grundkarte farbig'],
    center: [2611484, 1267592]
});
map.addMarker();
                

Ein Kartenausschnitt mit individuellen Marker-Punkten

const map = new mapbs.Map({
    div: 'map3',
    zoom: 4,
    center: [2611494, 1267592],
    showCoords: false
});
map.addMarker({
    position: [2611982, 1267773],
    size: [14, 14],
    icon: '/static/api/apihelp/img/info.png'
});
map.addMarker({
    position: [2611090, 1267875],
    size: [18, 18],
    icon: '/static/api/apihelp/img/essence.png'
});
map.addMarker({
    position: [2611500, 1267335],
    size: [14, 14],
    icon: '/static/api/apihelp/img/parking.png'
});
                

Ein Kartenausschnitt mit verschiedenen überlagerten Kartenebenen

const map = new mapbs.Map({
    div: 'map4',
    zoom: 4,
    center: [2611494, 1267592],
    layers: ['GL_AbschnittsStoergrade', 'SW_Jugendlichenanteil', 'KJ_Jugendangebot']
});
                

Ein Kartenausschnitt mit zusätzlichen Steuerelementen

const map = new mapbs.Map({
    div: 'map5',
    zoom: 4,
    center: [2611494, 1267592],
    layers: ['VO_TouristischeVelorouten_EuroVelo5', 'VO_TouristischeVelorouten_EuroVelo6', 'VO_TouristischeVelorouten_EuroVelo15'],
    addLayerSwitcher: true,
    addMiniMap: true,
    miniMapExpanded: true,
    showCoords: false
});
                

Verschieben der Kartenmitte, basierend auf gegebenen Koordinaten


const map_ = new mapbs.Map({
    div: 'map6',
    addMiniMap: true,
    zoom: 4,
    center: [2611494, 1267592],
    miniMapExpanded: true,
    showCoords:false
});
const button1 = document.getElementById('button1');
button1.onclick = function() {
    map_.recenter([2611527, 1267290], 7);
}
const button2 = document.getElementById('button2');
button2.onclick = function() {
    map_.recenter([2611773, 1266868], 7);
}
const button3 = document.getElementById('button3');
button3.onclick = function() {
    map_.recenter([2611494, 1267592], 4);
}
                

Verschieben der Kartenmitte, basierend auf einer Adresse


const map_ = new mapbs.Map({
    div: 'map7',
    zoom: 4,
    center: [2611494, 1267592],
    miniMapExpanded: true,
    showCoords:false
});
const addresses = [];

const inputElement = document.getElementById('address-search');
const datalist = document.getElementById('address-search-datalist');

inputElement.onkeyup = function(event) {
    datalist.innerHTML = '';
    if(event.key) {
        fetch(`https://search.geo.bs.ch/search?term=${inputElement.value}&maxresults=5`).then( function(response) {
            response.json().then(function(json) {
                json.forEach(function(option) {
                    const opt = document.createElement("OPTION");
                    opt.value = option.label;
                    datalist.appendChild(opt);
                    addresses.push(option);
                });
            });
        });
    }
};

inputElement.onchange = function(event) {
    const selectedAdress = addresses.find(function(item) { return item.label === inputElement.value});
    const point = selectedAdress.geom.replace('POINT (', '').replace(')', '').split(' ');
    const recenterPoints = point.map(function(item) { return parseInt(item)});
    map_.recenter([recenterPoints[0], recenterPoints[1]], 9);
    
};
                

Verschieben der Kartenmitte basierend auf Objekten

const map = new mapbs.Map({
    div: 'map8',
    zoom: 4,
    backgroundLayers: ['Grundkarte farbig'],
    layers: ['AS_Akutspitaeler']
});
map.recenterOnObjects(
    /* the layer name */
    'AS_Akutspitaeler',
    /* the ids of the objects */
    ['7','9'],
    /* whether to highlight the objects or not */
    false
);
                

Objekt abfragen

Klickt man auf ein Objekt, kann via JavaScript ein Popup angezeigt werden. Möchte man dieses Popup nicht nutzen, kann durch den Aufruf der mapbs.getMapbsFeatures() Methode die Eigenschaften des Objekts im JSON-Format abgerufen und ggf. weiterverarbeitet werden. Mit der Methode mapbs.setSelectionStyle() kann der Style der Markierung des Objektes verändert werden. Sie können auch eine WFS Filter Abfrage auf Attribute des WFS Layers machen, indem Sie die die Variable queryType='FILTER' setzen und entsprechend die Variable attribute dem Attributnamen des abzufragenden Attributes.


<div id='featureContainer' ></div>
Klicken Sie auf ein Objekt.
                    const map10 = new mapbs.Map({
                        div: 'map10',
                        zoom: 9,
                        center: [2611525, 1267284],
                        layers: ['DM_Gebaeudeinformationen_DatenmarktGebaeudeID_GebaeudeFertiggestellt']
                    });
                    // layer to be queried (if it is a wfs layer)
                    const layerName = 'DM_Gebaeudeinformationen_DatenmarktGebaeudeID_GebaeudeFertiggestellt';
                    // Set selection style (default is blue)
                    mapbs.setSelectionStyle(map10, strokeColor = 'rgb(255,255,0)', strokeWidth = 3, fillColor = 'rgba(255,255,0,0.1)');
                    // displays results of WFS Request in a popup
                    const showPopup = true;
                    // number of max. features to be returned
                    const maxFeatures = 1;
                    let queryType = 'BBOX';
                    let attribute = '';
                    let zoomToFeature = false;
                    // reacts on click in map
                    map10.map_.on('singleclick', function(event) {
                        let attributeValue = event.coordinate;
                        //returns object of wfs properties of selected feature -- whereas translations and exclude are both optional
                        mapbs.getMapbsFeatures(event, queryType, attribute, attributeValue, map10, layerName, showPopup, translations, exclude, 10).then(function (response) {
                            const properties = response[0];
                            //converts propteries object into json
                            const contentHTML_json = JSON.stringify(properties, function(key, value) {
                                // uses list of values to be excluded of json
                                if (exclude[key] !== undefined) {
                                    return undefined;
                                }
                                return value;
                            }, "
"); // display json of feature document.getElementById('featureContainer').innerHTML = "

Objekteigenschaften

" + contentHTML_json + "

"; }, function (error) { // no feature was found document.getElementById('featureContainer').innerHTML = "

Objekteigenschaften

" + error + "

"; }); }); // Keys of wfs properties usually have a technical name. Translations can be done here const translations = { "dm_gebaeudenummer": "Gebäude ID", "dm_gebaeudestatus": "Gebäudestatus", "dm_grundflaeche": "Gebäudegrundfläche [m²]", "dm_gebaeudekategorie": "Gebäudekategorie", "dm_adresse": "Adresse" }; // this dictionary is used to exclude specific properties from popup and json result const exclude = { "boundedBy": "", "dm_sektion": "", "dm_parzellennummer": "", "dm_gebaeudenummerbfs": "", "dm_koordinaten": "", "the_geom": "" }

Daten aus einer Text-Datei hinzufügen

Siehe: data.txt.
const map = new mapbs.Map({
    div: 'map11',
    zoom: 4,
    center: [2612222, 1267592],
    showCoords: true
});

map.addCustomLayer('text', 'My custom txt layer', '/static/api/apihelp/data.txt', {
    success: function() {
        map.selectObject(1);
        map.recenter([2612222, 1267592], 3);
    }
});
                

Punkte zeichnen


<div id='featureContainer' >
    <div id="point-coordinates">//Container für Punkt-Geometrien</div>
</div>
<div id='controlsContainer'>
    <button id='deletePoint'>Alle Punkte löschen</button>
</div>
                    
Klicken Sie in die Karte, um einen Punkt zu zeichnen.
const map = new mapbs.Map({
    div: 'map12',
    zoom: 4,
    center: [2612222, 1267592],
    showCoords: false
});

const deletePointBtn = document.getElementById("deletePoint");

const addPoint = function(event) {
    //get Points of Map, if needed
    //const points = map.vectorSource_.getFeatures();
    map.addMarker({
        position: event.coordinate,
        size: [14, 14],
        icon: '/static/api/apihelp/img/info.png'
    });
    const pointCoordinatesContainer = document.getElementById('point-coordinates');
    pointCoordinatesContainer.innerHTML = JSON.stringify(event.coordinate);
}
const deletePoint = function() {
    const points = map.vectorSource_.getFeatures();
    points.forEach(function(x) {
        map.vectorSource_.removeFeature(x);
    });
}

deletePointBtn.onclick = function(event) {
    deletePoint();
}
map.map_.on('singleclick', function(event) {
    addPoint(event); 
});
                    

Polygon zeichnen



    <button id="toggle_polygon">Polygon zeichnen</button>
    <!-- Map Container -->
    <div id='map13' ></div>
                    
const map = new mapbs.Map({
    div: 'map13', // id of the div element to put the map in
    zoom: 4,
    backgroundLayers: ['Grundkarte farbig'],
    center: [2611484, 1267592],
    crossOrigin: 'anonymous'
});

// Get Polygon element
const polygon_input = document.getElementById('polygon-input');

// Configure Draw Interactions
let drawInteraction;
let modifyInteraction;
const vector = new mapbs.VectorLayer({
    source: new mapbs.VectorSource({ wrapX: false }),
    map: map.map_,
    style: new mapbs.Style({
        fill: new mapbs.olStyleFill({
            color: [255, 255, 255, 0.6],
        }),
        stroke: new mapbs.olStyleStroke({
            color: [204, 51, 51, 1],
            width: 2
        }),
    }),
});

const addInteraction = function () {
    drawInteraction = new mapbs.Draw({
        source: vector.getSource(),
        type: 'Polygon',
    });
    map.map_.addInteraction(drawInteraction);
    modifyInteraction = new mapbs.olInteractionModify({
        source: vector.getSource(),
    });
    map.map_.addInteraction(modifyInteraction);

    const setCoordinates = function (event) {
        const feature = event.feature ? event.feature : event.features.array_[0];
        coordinates = feature.getGeometry().getCoordinates()[0].map(function (x) {
            return Math.round(x[0] * 1000) / 1000 + '/' + Math.round(x[1] * 1000) / 1000;
        }).toString()
    };
    const setAllCoordinates = function (event) {
        const features = vector.getSource().getFeatures();
        if (features.length) {
            features.forEach(function (f) {
                return vector.getSource().removeFeature(f);
            })
        }
    }
    drawInteraction.on('drawend', setCoordinates);
    modifyInteraction.on('modifyend', setCoordinates);

    drawInteraction.on('drawstart', setAllCoordinates);
}
polygon_toggled = false;
toggle_polygon.onclick = function () {
    if (polygon_toggled) {
        map.map_.removeInteraction(drawInteraction);
        map.map_.removeInteraction(modifyInteraction);
        polygon_toggled = false;
    } else {
        addInteraction();
        polygon_toggled = true;
    }
}