This content applies to a previous version of CARTO
In October 2021 we released a new version of our platform. You can find the latest documentation at docs.carto.com
How can you search your own CARTO dataset in a CARTO.js map?
Overview
The example demonstrates creating a map with a dropdown menu listing country names from the ne_adm0_europe CARTO dataset’s admin field. Selecting a country from the dropdown adjusts the map’s zoom level and center to fit the selected country’s bounding box.
Implementation Steps
- Create a CARTO.js map with one layer
- Build a
populateDropDown()function that uses the CARTO SQL API to retrieve geometry and names from the dataset, then populates the HTML<select>dropdown - Make another SQL API request to retrieve data for the selected country and use mapping library methods to fit the map bounds
CARTO SQL API Request
The implementation uses the JavaScript Fetch API to query CARTO’s SQL API. Alternative libraries like Axios or jQuery can be used for broader browser compatibility.
Leaflet Approach
Uses L.geoJson() to convert API response data, then applies getBounds() and fitBounds() methods:
document.getElementById('selectDrop').addEventListener("change", function (e) {
input = e.currentTarget.selectedOptions[0].attributes[0].value;
return fetch(`https://cartojs-test.carto.com/api/v2/sql?format=geojson&q=SELECT * FROM ne_adm0_europe where admin Ilike '${input}'`)
.then((resp) => resp.json())
.then((response) => {
geojsonLayer = L.geoJson(response)
map.fitBounds(geojsonLayer.getBounds());
})
});
Google Maps Approach
Retrieves bounding box coordinates using PostGIS methods (ST_Envelope, ST_Xmax, ST_Ymax, ST_Xmin, ST_Ymin), then applies Google Maps coordinate objects:
document.getElementById('selectDrop').addEventListener("change", function (e) {
input = e.currentTarget.selectedOptions[0].attributes[0].value;
return fetch(`https://cartojs-test.carto.com/api/v2/sql?format=geojson&q=
WITH bbox as (
SELECT ST_Envelope(the_geom) as the_geom
FROM ne_adm0_europe
WHERE admin Ilike '${input}'
)
SELECT the_geom, ST_Xmax(the_geom) as xmax,
ST_Ymax(the_geom) as ymax,
ST_Xmin(the_geom) as xmin,
ST_Ymin(the_geom) as ymin
FROM bbox`)
.then((resp) => resp.json())
.then((response) => {
coordinates = response['features'][0].properties
let sw = new google.maps.LatLng(coordinates.ymin, coordinates.xmin);
let ne = new google.maps.LatLng(coordinates.ymax, coordinates.xmax);
bounds = new google.maps.LatLngBounds(sw, ne)
map.fitBounds(bounds);
})
});
