I have a search input that populates suggestions in a div below it while the user is typing and I'd like to add an event listener to the suggestion div. The problem is when the page loads the suggestion div isn't populated with anything because the user hasn't typed anything in the search input yet and it throws
TypeError: searchSugg is undefined
Is there a way around this? I tried wrapping the listener in if (searchSugg !== undefined) {...}
and though it doesn't throw an error it also doesn't run the addEventListener
function.
Code:
var searchSugg = document.getElementsByClassName('mapboxgl-ctrl-geocoder--suggestion')[0];
searchSugg.addEventListener('click', function() {
// // Create variables to use in isochrone API
var urlBase = 'https://api.mapbox.com/isochrone/v1/mapbox/';
var lng = geocoder.mapMarker._lngLat.lng;
var lat = geocoder.mapMarker._lngLat.lat;
var profile = 'cycling';
var minutes = 10;
// Create a function that sets up the Isochrone API query then makes an Ajax call
var query = urlBase + profile + '/' + lng + ',' + lat + '?contours_minutes=' + minutes + '&polygons=true&access_token=' + mapboxgl.accessToken;
$.ajax({
method: 'GET',
url: query
}).done(function(data) {
map.getSource('iso').setData(data);
})
map.addSource('iso', {
type: 'geojson',
data: {
'type': 'FeatureCollection',
'features': []
}
});
map.addLayer({
'id': 'isoLayer',
'type': 'fill',
// Use "iso" as the data source for this layer
'source': 'iso',
'layout': {},
'paint': {
// The fill color for the layer is set to a light purple
'fill-color': '#5a3fc0',
'fill-opacity': 0.3
}
}, "poi-label");
});