原文链接及内容
示例介绍:一个在地图渲染CartoDB数据的例子。使用 CartoDB 数据源动态显示欧洲国家数据,并通过用户选择的面积阈值过滤显示的国家区域。
实现方法:通过 HTML 元素(areaSelect)动态更新 CartoDB 的 SQL 查询,重新渲染图层。
关于cartodb map,请阅读以下资料进一步了解:
- https://cartodb.github.io/developers/
- https://cartodb.github.io/developers/maps-api/

main.js
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| import Map from 'ol/Map.js'; import TileLayer from 'ol/layer/Tile.js'; import View from 'ol/View.js'; import {CartoDB, OSM} from 'ol/source.js';
const mapConfig = { 'layers': [ { 'type': 'cartodb', 'options': { 'cartocss_version': '2.1.1', 'cartocss': '#layer { polygon-fill: #F00; }', }, }, ], };
function setArea(n) { mapConfig.layers[0].options.sql = 'select * from european_countries_e where area > ' + n; } const areaSelect = document.getElementById('country-area'); setArea(areaSelect.value);
const cartoDBSource = new CartoDB({ account: 'documentation', config: mapConfig, });
areaSelect.addEventListener('change', function () { setArea(this.value); cartoDBSource.setConfig(mapConfig); });
const map = new Map({ layers: [ new TileLayer({ source: new OSM(), }), new TileLayer({ source: cartoDBSource, }), ], target: 'map', view: new View({ center: [8500000, 8500000], zoom: 2, }), });
|
界面布局文件index.html
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CartoDB source example</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="node_modules/ol/ol.css"> <style> .map { width: 100%; height: 400px; } </style> </head> <body> <div id="map" class="map"></div> <form class="row"> <div class="col-auto"> <div class="input-group"> <label for="country-area" class="input-group-text">显示的欧洲国家面积大于:</label> <select id="country-area" class="form-select"> <option value="0" default>0 ㎢</option> <option value="5000">5000 ㎢</option> <option value="10000">10000 ㎢</option> <option value="50000">50000 ㎢</option> <option value="100000">100000 ㎢</option> </select> </div> </div> </form> <script src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script> <script type="module" src="main.js"></script> </body> </html>
|