Skip to content

Instantly share code, notes, and snippets.

@alasarr
Last active November 5, 2019 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alasarr/e80378614d4290b970cf25ccdb17c377 to your computer and use it in GitHub Desktop.
Save alasarr/e80378614d4290b970cf25ccdb17c377 to your computer and use it in GitHub Desktop.
Fetch data by random polygon
<!DOCTYPE html>
<html>
<head>
<title> Filter data on map | CARTO</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Open+Sans:300,400,600" rel="stylesheet">
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" rel="stylesheet">
<!-- Include Leaflet Draw plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.13/leaflet.draw.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.13/leaflet.draw.css" />
<!-- Include CARTO.js -->
<script src="https://libs.cartocdn.com/carto.js/v4.1.11/carto.min.js"></script>
<link href="https://carto.com/developers/carto-js/examples/maps/public/style.css" rel="stylesheet">
</head>
<body>
<!-- map element -->
<div id="map"></div>
<!-- Description -->
<aside class="toolbox">
<div class="box">
<header>
<h1>Filter data based on polygon or circle</h1>
<button class="github-logo js-source-link"></button>
</header>
<section>
<p class="description open-sans">Filter data based on drawn polygon or cycle.</p>
<p class="description open-sans" id="result" style='color: #f00' ></p>
</section>
<footer class="js-footer"></footer>
</div>
</aside>
<script>
// set map with initial zoom and coodinates view
const map = L.map('map').setView([40, -80], 7);
// disable scroll wheel zoom
map.scrollWheelZoom.disable();
// add basemaps to map
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
// set CARTO client
const client = new carto.Client({
apiKey: 'default_public',
username: 'cartojs-test'
});
// set SQL query to create the grid of hexagons
const source = new carto.source.SQL(`
SELECT * FROM ne_10m_populated_places_simple
`);
// define styles of layer.
const style = new carto.style.CartoCSS(`
#layer {
marker-fill: red;
}
`);
// set the CARTO layer using the source and style defines previously
const layer = new carto.layer.Layer(source, style);
// add CARTO layer to the client
client.addLayer(layer);
client.getLeafletLayer().addTo(map);
let drawControl = new L.Control.Draw({
draw: {
polygon: true,
polyline: false,
line: false,
marker: false,
rectangle: false,
circle: {
shapeOptions: {
color: 'green',
weight: 0.1,
opacity: 0.5
}
},
circlemarker: false,
},
edit: false
});
// initialise the draw controls
map.addControl(drawControl);
// get radius and center of drawn circle and change source of the CARTO layer
map.on(L.Draw.Event.CREATED, function (e, d) {
debugger;
let layer = e.layer;
map.addLayer(layer);
if (e.layerType == 'circle'){
let radius = layer.getRadius();
let centerLat = layer.getLatLng().lat;
let centerLng = layer.getLatLng().lng;
circle_query = fetchCircle(radius, centerLat, centerLng);
}
else if (e.layerType == 'polygon'){
let geojson = JSON.stringify(layer.toGeoJSON()['geometry']);
fetchPolygon(geojson);
}
});
function runQuery(q){
fetch(`https://cartojs-test.carto.com/api/v2/sql?q=${q}`)
.then((resp) => resp.json())
.then((response) => {
// we get the data from the request response
let r = response.rows[0];
document.getElementById('result').innerHTML = `Total places: ${r.n}<br/>Total pop: ${r.pop}`;
})
.catch(function (error) {
// check if the request is returning an error
console.log(error)
});
}
function fetchCircle(radius, lat,lng){
q = `
SELECT count(*) as n, sum(pop_max) as pop
FROM ne_10m_populated_places_simple
WHERE ST_intersects(
the_geom,
ST_Buffer(
ST_SetSRID(ST_Point(${lng},${lat}),4326)::geography,
${radius})::geometry
)
`;
runQuery(q);
};
function fetchPolygon(geojson){
q = `
SELECT count(*) as n, sum(pop_max) as pop
FROM ne_10m_populated_places_simple
WHERE ST_intersects(
the_geom,
ST_SetSRID(ST_GeomFromGeoJSON('${geojson}'), 4326)
)
`;
runQuery(q);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment