Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dropdown + setQuery | CARTO.js
<!DOCTYPE html>
<html>
<head>
<title>Dropdown + setQuery | CARTO.js</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<!-- Include jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" rel="stylesheet">
<!-- Include CARTO.js -->
<script src="https://libs.cartocdn.com/carto.js/v4.0.8/carto.min.js"></script>
<style type="text/css">
html,
body {
height: 100%;
padding: 0;
margin: 0;
position: relative;
}
#map {
height: 100%;
padding: 0;
margin: 0;
}
#wraper-dropdown-selector {
position: absolute;
top: 20px;
right: 20px;
z-index: 999;
}
.js-dropdown-selector {
width: 160px;
}
</style>
</head>
<body>
<div id="map"></div>
<!-- dropdown selector -->
<div id="wraper-dropdown-selector">
<select class="js-dropdown-selector">
<option value="all" selected>All cities</option>
<option value="megacity">Megacities</option>
</select>
</div>
<script>
const map = L.map('map').setView([40, -3], 2);
map.scrollWheelZoom.disable();
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
const client = new carto.Client({
apiKey: 'default_public',
username: 'cartojs-test'
});
const source = new carto.source.SQL(`
SELECT * FROM ne_10m_populated_places_simple
`);
const style = new carto.style.CartoCSS(`
#layer {
marker-width: ramp([pop_max], range(2,11), quantiles(7));
marker-fill: ramp([featurecla], cartocolor(Bold), category(7));
marker-opacity: 0.9;
marker-line-color: #FFFFFF;
marker-line-opacity: 0.7;
}
`);
const layer = new carto.layer.Layer(source, style);
client.addLayer(layer);
client.getLeafletLayer().addTo(map);
const selector = $(".js-dropdown-selector");
// change sql query with dropdown value
selector.on('change', function(e) {
let value = e.target.value;
console.log(value);
if (value == 'megacity') {
source.setQuery(`SELECT * FROM ne_10m_populated_places_simple where pop_max > 5000000`);
} else {
source.setQuery(`SELECT * FROM ne_10m_populated_places_simple`);
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.