Skip to content

Instantly share code, notes, and snippets.

@vaertsen
Created May 18, 2017 07:46
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 vaertsen/6e8be4eb49a5b7434eda8d4cb883013f to your computer and use it in GitHub Desktop.
Save vaertsen/6e8be4eb49a5b7434eda8d4cb883013f to your computer and use it in GitHub Desktop.
Obtain info from polygon that intersects with marker [CARTO]
<!DOCTYPE html>
<html>
<head>
<title>Obtain info from polygon that intersects with marker</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- include cartodb.js and cartodb.css library -->
<link rel="stylesheet" href="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
<style>
html, body, #map {
height: 100%;
width:100%;
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<!-- MAP -->
<div id="map"></div>
<script>
// main function
function main() {
// basic variables
var userName = "victor-aertsen";
var newMarker;
// map object
var map_object = new L.Map('map', {
center: [40.41637, -3.70342],
zoom: 8,
zoomControl: false
});
// set the popup information: latlng and municipality name
function findMunicipality (marker) {
// Obtain the name of the minicipality
var jsonQuery = "https://" + userName + ".carto.com/api/v2/sql?format=GeoJSON&q=SELECT nameunit, the_geom FROM ign_spanish_adm3_municipalities WHERE ST_Intersects(the_geom, ST_GeomFromText('POINT(" + marker.getLatLng().lng + " " + marker.getLatLng().lat + ")', 4326))"
$.getJSON(jsonQuery).done( function (result_data) {
var popup_text = "<b>Latlng:</b> " + marker.getLatLng().lat + ", " + marker.getLatLng().lng +
"</br><b>Municipality:</b> " + result_data.features[0].properties.nameunit;
marker.bindPopup(popup_text).openPopup();
});
}
// define base map
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {attribution: 'OSM'})
.addTo(map_object);
// add new marker on click
map_object.on('click', function(e) {
// removes old marker
if (newMarker) {
map_object.removeLayer(newMarker);
}
// add draggable marker
newMarker = L.marker([e.latlng.lat, e.latlng.lng], {draggable: true})
.addTo(map_object)
.on('dragend', function(e) {
// add popup information on dragged marker
findMunicipality(newMarker);
});
// add popup information on new marker
findMunicipality(newMarker);
});
}
// initiates the map
window.onload = main;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment