Skip to content

Instantly share code, notes, and snippets.

@ivanmalagon
Last active March 12, 2018 10:12
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 ivanmalagon/4c6607df493cca652624e094568593ec to your computer and use it in GitHub Desktop.
Save ivanmalagon/4c6607df493cca652624e094568593ec to your computer and use it in GitHub Desktop.
Get bounds in CARTO.js
<!DOCTYPE html>
<html>
<head>
<title>Bounds example | CARTO</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<!-- 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://cartodb-libs.global.ssl.fastly.net/carto.js/v4.0.0-beta.25/carto.min.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; height: 100%; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = L.map('map').setView([40, 0], 5);
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
const apiKey = 'YOUR_API_KEY';
const username = 'cartojs-test'
const client = new carto.Client({ apiKey, username });
const whereQuery = 'FROM ne_10m_populated_places_simple WHERE adm0name= \'Spain\'';
const citiesSource = new carto.source.SQL(`SELECT * ${whereQuery}`);
const citiesStyle = new carto.style.CartoCSS(`
#layer {
marker-width: 16;
marker-fill: #EE4D5A;
marker-line-color: #FFFFFF;
}
`);
const citiesLayer = new carto.layer.Layer(citiesSource, citiesStyle, {
featureClickColumns: ['name']
});
client.addLayer(citiesLayer);
client.getLeafletLayer().addTo(map);
const query = `SELECT ST_Extent(the_geom) as extent ${whereQuery}`;
const boundsUrl = `https://${username}.carto.com/api/v2/sql?q=${query}&api_key=${apiKey}`
fetch(boundsUrl)
.then(response => {
return response.json()
})
.then(json => {
const extent = json.rows[0].extent;
const bounds = parseExtent(extent);
console.log(extent);
console.log(bounds);
map.fitBounds(
[
[bounds.south, bounds.west],
[bounds.north, bounds.east]
]
);
});
// From BOX(-179.5 -89.9,179.3 82.3) to bounds object
function parseExtent (extent) {
const floatRegex = /-?[0-9]\d*(\.\d+)?/g;
const matches = extent.match(floatRegex);
return {
west: Number.parseFloat(matches[0]),
south: Number.parseFloat(matches[1]),
east: Number.parseFloat(matches[2]),
north: Number.parseFloat(matches[3])
};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment