Skip to content

Instantly share code, notes, and snippets.

@javisantana
Created October 22, 2014 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save javisantana/d20063afd2c96a733002 to your computer and use it in GitHub Desktop.
Save javisantana/d20063afd2c96a733002 to your computer and use it in GitHub Desktop.
highlight polygon on click with leaflet and cartodb.js
<!DOCTYPE html>
<html>
<head>
<title>Leaflet example | CartoDB.js</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" href="http://cartodb.com/assets/favicon.ico" />
<style>
html, body, #map {
height: 100%;
padding: 0;
margin: 0;
}
</style>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/themes/css/cartodb.css" />
</head>
<body>
<div id="map"></div>
<!-- include cartodb.js library -->
<script src="http://libs.cartocdn.com/cartodb.js/v3/cartodb.js"></script>
<script>
function main() {
var map = new L.Map('map', {
zoomControl: false,
center: [43, 0],
zoom: 3
});
var sql = new cartodb.SQL({ user: 'documentation', format: 'geojson' });
var polygon;
function showFeature(cartodb_id) {
sql.execute("select ST_Simplify(the_geom, 0.1) as the_geom from european_countries_e where cartodb_id = {{cartodb_id}}", {cartodb_id: cartodb_id} ).done(function(geojson) {
if (polygon) {
map.removeLayer(polygon);
}
polygon = L.geoJson(geojson, {
style: {
color: "#000",
fillColor: "#fff",
weight: 2,
opacity: 0.65
}
}).addTo(map);
});
}
L.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
attribution: 'Stamen'
}).addTo(map);
cartodb.createLayer(map, 'http://documentation.cartodb.com/api/v2/viz/2b13c956-e7c1-11e2-806b-5404a6a683d5/viz.json', { infowindow: false })
.addTo(map)
.on('done', function(layer) {
layer.setInteraction(true);
layer.on('featureClick', function(e, pos, latlng, data) {
showFeature(data.cartodb_id)
});
}).on('error', function() {
cartodb.log.log("some error occurred");
});
}
// you could use $(window).load(main);
window.onload = main;
</script>
</body>
</html>
@MemberSense
Copy link

MemberSense commented Oct 17, 2016

Once a feature is highlighted, clicking it has no effect. Is there another event, similar to featureClick, which is triggered when a selected feature (point, line or polygon) is clicked again? Thanks for the great examples Javi!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment