Last active
March 19, 2020 19:24
-
-
Save alroba/8b862633705c68e32e614dbae2729712 to your computer and use it in GitHub Desktop.
Change polygon border color
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="viewport" content="width=device-width"> | |
<!-- Include Carto.js --> | |
<script src="https://libs.cartocdn.com/carto.js/v4.1.8/carto.min.js"></script> | |
<!-- Include Leaflet --> | |
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script> | |
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"> | |
<!-- Adding Axios --> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script> | |
<style> | |
#map { | |
width: 100%; | |
height: 100vh; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="map"></div> | |
<script> | |
const map = L.map('map').setView([41.38, 2.18], 11); | |
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', { | |
maxZoom: 18 | |
}).addTo(map); | |
// define client | |
const client = new carto.Client({ | |
apiKey: 'default_public', | |
username: 'oboix' | |
}); | |
console.log('miau') | |
// define source of data using a SQL query | |
const source = new carto.source.SQL(` | |
SELECT * FROM districtes_barcelona | |
`); | |
// define CartoCSS code to style data on map | |
const style = new carto.style.CartoCSS(` | |
#layer{ | |
polygon-fill: tomato; | |
} | |
`); | |
// create CARTO layer from source and style variables | |
const cartoLayer = new carto.layer.Layer(source, style, { | |
featureClickColumns: ['cartodb_id'] | |
}); | |
cartoLayer.on('featureClicked', function (featureEvent) { | |
let polygon_selected = featureEvent.data.cartodb_id; | |
// call with CARTO SQL API the layer that we want to use, | |
// we get the boundaries of the polygons to highlight them when click | |
axios.get(`https://oboix.carto.com/api/v2/sql?q= | |
SELECT ST_asGeoJSON(ST_Boundary(the_geom)) as geom | |
FROM districtes_barcelona | |
WHERE cartodb_id = ${polygon_selected} | |
`).then(function (response) { | |
// save into geom the geometriea that come from CARTO | |
let geom = response.data.rows[0].geom; | |
// style | |
let boundary = L.geoJson(JSON.parse(geom), { | |
style: { | |
color: "#000", | |
weight: 5 | |
} | |
}); | |
// add Leaflet layer to the map | |
map.addLayer(boundary); | |
}) | |
}) | |
// add CARTO layer to the client | |
client.addLayer(cartoLayer); | |
// get tile from client and add them to the map object | |
client.getLeafletLayer().addTo(map); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment