Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <body>
    <div class='map-view'>
        <form class='tt-side-panel js-form'>
            <header class='tt-side-panel__header'>
                <div class='input-wrappper'>
                    <div class='tt-icon icon-spacing -start'></div>
                    <div id='startSearchBox' class='tt-form-label searchbox'></div>
                </div>
                <div class='input-wrappper'>
                    <div class='tt-icon icon-spacing -finish'></div>
                    <div id='finishSearchBox' class='tt-form-label searchbox'></div>
                </div>
              <div class= "tt-timeinput"> 

       <label class='tt-label'>Driving Time Interval</label> 

       <input id='timebudget' class='tt-input' type='number' value='2000'> 

   </div> 

        <div class='tt-spacing-top-24'> 

        <input id='submit-button' type='submit' class='tt-button -primary tt-spacing-top-24' name='submit' value='Find Region'> 
           <input id='submit-button-clear' type='submit' class='tt-button -primary tt-spacing-top-24' name='submit-clear' value='Remove Region'>

   </div>	
            </header>
            <div class='tt-tabs js-tabs'>
                <div class='tt-tabs__panel'>
                    <div class='tt-results-list'>
                        <li class='tt-results-list__item'><div class='result-header'>Rest Stops:</div></li>
                    </div>
                    <div class='tt-tabs__placeholder'>
                        To try out this app, enter your TomTom API key at the JavaScript code line 2.
                    </div>
                </div>
            </div>
        </form>
        <div id='map' class='full-map'></div>
    </div>
</body>
              
            
!

CSS

              
                
        
        .map-view .icon {
            height: 30px;
            width: 30px;
        }
        .map-view .tt-icon.-finish {
            height: 16px;
            width: 16px;
        }
        .map-view .icon-spacing {
            margin-right: 14px;
            margin-top: 24px;
        }
        .map-view .searchbox {
            flex: 1;
        }
        .map-view .tt-results-list {
            display: none;
            max-height: 100%;
            overflow-y: auto;
        }
        .map-view .tt-results-list__item {
            display: flex;
            font-size: 12px;
            justify-content: space-between;
        }
        .map-view .tt-results-list__item:first-child {
            cursor: default;
            font-size: 16px;
            font-weight: bold;
        }
        .map-view .supporting-marker {
            align-items: center;
            background-color: #4a90e2;
            border: solid 3px #2faaff;
            border-radius: 50%;
            display: flex;
            height: 32px;
            justify-content: center;
            transition: width .1s, height .1s;
            width: 32px;
        }
        .map-view .supporting-marker.-big,
        .map-view .supporting-marker.-selected {
            height: 42px;
            width: 42px;
            z-index: 15;
        }
        .map-view .supporting-marker .supporting-circle {
            border: 1px solid #ffffff;
            border-radius: 50%;
            height: 13px;
            width: 13px;
        }
        .map-view .tt-tabs .tt-tabs__placeholder {
            font-size: 15px;
        }
        .map-view .input-wrappper {
            display: flex;
            min-height: 52px;
        }
        .remove-btn {
            background-color: transparent;
            border: 0;
            cursor: pointer;
            margin-left: 10px;
        }
    
        html {
            height:100%;
        }
      .tt-label{ 

            width:160px 

        } 

    .tt-timeinput{ 

            align-items: center;  

            display: flex;  

            margin-top: 12px; 

        } 
              
            
!

JS

              
                tt.setProductInfo('Codepen Examples', '${analytics.productVersion}');
var myKey = 'replace-with-your-api-key';
var map = tt.map({
    key: myKey,
    container: 'map',
    dragPan: !isMobileOrTablet()
});
map.addControl(new tt.FullscreenControl({ container: document.querySelector('body') }));
map.addControl(new tt.NavigationControl());
var errorHint = new InfoHint('error', 'bottom-center', 5000).addTo(document.getElementById('map'));
var loadingHint = new InfoHint('info', 'bottom-center').addTo(document.getElementById('map'));
var infoHint = new InfoHint('info', 'bottom-center', 5000).addTo(document.getElementById('map'));
// example data
var route = {
    start: [-8.4292, 40.21149],
    finish: [-3.70034, 40.41669]
};
var startMarker;
var endMarker;
var supportingPoints = [];
var resultItemSelected;
var markerSelected;
var abortController;
var resultList = document.querySelector('.tt-results-list');
var noResultsDiv = document.querySelector('.tt-tabs__placeholder');
// calculate route methods
function findFirstBuildingLayerId() {
    var layers = map.getStyle().layers;
    for (var index in layers) {
        if (layers[index].type === 'fill-extrusion') {
            return layers[index].id;
        }
    }
    throw new Error('Map style does not contain any layer with fill-extrusion type.');
}
function createMarkerElement(type) {
    var element = document.createElement('div');
    element.className = 'supporting-marker';
    var innerElement = document.createElement('div');
    innerElement.className = type !== 'supporting' ? 'tt-icon -white -' + type : 'supporting-circle';
    element.appendChild(innerElement);
    return element;
}
function addRouteMarkers(feature) {
    if (startMarker) {
        startMarker.remove();
    }
    if (endMarker) {
        endMarker.remove();
    }
    var startPoint, endPoint;
    if (feature.geometry.type === 'MultiLineString') {
        startPoint = feature.geometry.coordinates[0][0]; //get first point from first line
        endPoint = feature.geometry.coordinates.slice(-1)[0].slice(-1)[0]; //get last point from last line
    } else {
        startPoint = feature.geometry.coordinates[0];
        endPoint = feature.geometry.coordinates.slice(-1)[0];
    }
    startMarker = new tt.Marker({ element: createMarkerElement('start') }).setLngLat(startPoint).addTo(map);
    endMarker = new tt.Marker({ element: createMarkerElement('finish') }).setLngLat(endPoint).addTo(map);
}
function clearMap() {
    if (map.getLayer('route')) {
        map.removeLayer('route');
        map.removeSource('route');
    }
}
function drawRoute(fitBounds) {
    if (!route.start || !route.finish) {
        return;
    }
    if (abortController) {
        abortController.abort();
    }
    abortController = new AbortController();
    loadingHint.setMessage('Loading...');
    var preparedSupportingPoints = supportingPoints.map(function(supportingPoint) {
        return supportingPoint.position.join();
    });
    var calculateRouteData = {
        key: myKey,
        traffic: false,
        supportingPoints: preparedSupportingPoints.length > 1 ? preparedSupportingPoints : undefined,
        locations: route.start.join() + ':' + route.finish.join()
    };
    (function() {
        var signal = abortController.signal;
        tt.services.calculateRoute(calculateRouteData, { abortSignal: signal })
            .then(function(response) {
                clearMap();
                var geojson = response.toGeoJson();
                map.addLayer({
                    'id': 'route',
                    'type': 'line',
                    'source': {
                        'type': 'geojson',
                        'data': geojson
                    },
                    'paint': {
                        'line-color': '#4a90e2',
                        'line-width': 6
                    }
                }, findFirstBuildingLayerId());
                addRouteMarkers(geojson.features[0]);
                if (fitBounds) {
                    var bounds = new tt.LngLatBounds();
                    geojson.features[0].geometry.coordinates.forEach(function(point) {
                        bounds.extend(tt.LngLat.convert(point));
                    });
                    map.fitBounds(bounds, { duration: 0, padding: 50 });
                }
                loadingHint.hide();
            }).catch(function() {
                if (signal.aborted === true) {
                    return;
                }
                clearMap();
                errorHint.setMessage('There was a problem calculating the route');
                loadingHint.hide();
            });
    })();
}
// handling searchbox input
function onResultSelected(result, type) {
    var position = result.position;
    route[type] = [position.lng, position.lat];
    drawRoute(true);
}
function onResultCleared(type) {
    startMarker.remove();
    endMarker.remove();
    route[type] = undefined;
    clearMap();
}
function createSearchBox(type) {
    var searchBox = new tt.plugins.SearchBox(tt.services, {
        showSearchButton: false,
        searchOptions: {
            key: myKey
        },
        labels: {
            placeholder: 'Query e.g. London'
        }
    });
    document.getElementById(type + 'SearchBox').appendChild(searchBox.getSearchBoxHTML());
    searchBox.on('tomtom.searchbox.resultscleared', onResultCleared.bind(undefined, type));
    searchBox.on('tomtom.searchbox.resultsfound', function(event) {
        handleEnterSubmit(event, onResultSelected.bind(this), errorHint, type);
    });
    searchBox.on('tomtom.searchbox.resultselected', function(event) {
        if (event.data && event.data.result) {
            onResultSelected(event.data.result, type);
        }
    });
    return searchBox;
}
function toggleResultsVisibility(resultsVisible) {
    resultList.style.display = resultsVisible ? 'block' : 'none';
    noResultsDiv.style.display = resultsVisible ? 'none' : 'block';
}
// handling map clicks - adding markers and using reverse geocode to find the address
function createDeleteButton(listener) {
    var button = document.createElement('button');
    button.className = 'tt-icon icon-spacing-left remove-btn -trash -black';
    if (listener) {
        button.addEventListener('click', listener);
    }
    return button;
}
function deleteHandler(resultItem, marker, address, e) {
    e.preventDefault();
    resultList.removeChild(resultItem);
    supportingPoints = supportingPoints.filter(function(supportingPoint) {
        return supportingPoint.id !== address.id;
    });
    marker.remove();
    drawRoute();
    if (supportingPoints.length < 2) {
        infoHint.setMessage('You need to have at least 2 supporting points selected');
    }
    if (supportingPoints.length === 0) {
        toggleResultsVisibility(false);
    }
    if (resultItemSelected) {
        resultItemSelected.classList.remove('-selected');
        resultItemSelected = undefined;
    }
}
function selectResultMarkerPair(resultItem, marker, scroll) {
    if (markerSelected) {
        markerSelected.getElement().classList.remove('-selected');
    }
    marker.getElement().classList.add('-selected');
    markerSelected = marker;
    if (resultItemSelected) {
        resultItemSelected.classList.remove('-selected');
    }
    resultItem.classList.add('-selected');
    if (scroll && resultItem && resultItem.parentNode) {
        resultItem.parentNode.scrollTop = resultItem.offsetTop - resultItem.parentNode.offsetTop;
    }
    resultItemSelected = resultItem;
}
function appendResultListEvents(resultItem, marker) {
    resultItem.addEventListener('mouseover', function() {
        marker.getElement().classList.add('-big');
    });
    resultItem.addEventListener('mouseout', function() {
        marker.getElement().classList.remove('-big');
    });
    resultItem.addEventListener('click', selectResultMarkerPair.bind(null, resultItem, marker));
    marker.getElement().addEventListener('click', selectResultMarkerPair.bind(null, resultItem, marker, true));
}
function handleReverseGeocodeResult(revGeoResponse) {
    var firstAddress = revGeoResponse.addresses[0];
    if (!firstAddress || !firstAddress.address || !firstAddress.address.freeformAddress) {
        loadingHint.hide();
        errorHint.setMessage('Address not found, please choose a different place');
        return;
    }
    var lngLat = [firstAddress.position.lng, firstAddress.position.lat];
    var marker = new tt.Marker(createMarkerElement('supporting')).setLngLat(lngLat).addTo(map);
    var address = {
        id: Date.now(),
        address: firstAddress.address.freeformAddress,
        position: [firstAddress.position.lng, firstAddress.position.lat],
        marker: marker
    };
    supportingPoints.push(address);
    toggleResultsVisibility(true);
    var resultItem = DomHelpers.createResultItem();
    var addressDiv = document.createElement('div');
    addressDiv.innerText = firstAddress.address.freeformAddress;
    resultItem.appendChild(addressDiv);
    var deleteButton = createDeleteButton(deleteHandler.bind(null, resultItem, marker, address));
    resultItem.appendChild(deleteButton);
    resultList.appendChild(resultItem);
    appendResultListEvents(resultItem, marker);
    if (supportingPoints.length > 1) {
        drawRoute();
    }
}
function onMapClick(e) {
    infoHint.hide();
    if (e.originalEvent.target.classList.contains('supporting-marker') ||
        e.originalEvent.target.classList.contains('tt-icon') ||
        e.originalEvent.target.classList.contains('supporting-circle')) {
        return;
    }
    if (supportingPoints.length < 1 && !errorHint.isHidden()) {
        infoHint.setMessage('You need to have at least 2 supporting points selected');
    }
    if (supportingPoints.length > 1 && route.start && route.finish) {
        loadingHint.setMessage('Loading...');
    }
    errorHint.hide();
    tt.services.reverseGeocode({
        key: '1tN8sunxVpQgWhZjVWXLcR6fzIdLzGXZ',
        position: e.lngLat.toArray(),
        language: 'en-GB'
    }).then(handleReverseGeocodeResult);
}
// init
map.on('load', function() {
    var startSearchBox = createSearchBox('start');
    var finishSearchBox = createSearchBox('finish');
    map.on('click', onMapClick);
    startSearchBox.getSearchBoxHTML().querySelector('input.tt-search-box-input').value = 'Coimbra';
    finishSearchBox.getSearchBoxHTML().querySelector('input.tt-search-box-input').value = 'Madrid';
    drawRoute(true);
});
function handleServiceResponse(serviceData, response) { 

            var bounds = new tt.LngLatBounds(); 

            var groupedResponseData = {}; 

            response.batchItems.forEach(function(polygonData, i) { 

                var localtionData = serviceData[i]; 

                var polygon = polygonData.toGeoJson(); 

 
 

                if (!Array.isArray(groupedResponseData[localtionData.location])) { 

                    groupedResponseData[localtionData.location] = []; 

                } 

                groupedResponseData[localtionData.location].push({ 

                    localtionData: localtionData, 

                    polygon: polygon 

                }); 

                polygon.geometry.coordinates[0].forEach(function(point) { 

                    bounds.extend(tt.LngLat.convert(point)); 

                }); 

            }); 

            drawPolygon(groupedResponseData); 

            map.fitBounds(bounds, { padding: 50 }); 

        } 

 
 

   function drawPolygon(groupedResponseData) { 

             Object.keys(groupedResponseData).slice().reverse().forEach(function(locationName, i) { 

                var locationData = groupedResponseData[locationName]; 

                var polygonLayers = []; 

 
 

                locationData.forEach(function(data, i) { 

                    map.addLayer({ 

                        'id': locationName, 

                        'type': 'fill', 

                        'source': { 

                            'type': 'geojson', 

                            'data': data.polygon 

                        }, 

                        'paint': { 

                            'fill-color': '#006967', 

                            'fill-opacity': 0.7 

                        } 

                    }); 

                    polygonLayers.push({ 

                        id: locationName, 

                        color: '#006967' 

                        }); 

                    }); 

                    layersOnTheMap[locationName] = polygonLayers; 

                    var polygonMarker = new tt.Marker().setLngLat(OriginPoint[locationName]).addTo(map); 

                    polygonMarker.setPopup(new tt.Popup({ offset: 30 }).setText(locationName)); 

                    polygonMarker.getElement().addEventListener('click', function() { 

                        layersOnTheMap(function(layer) { 

                        map.setPaintProperty(layer.id, 'fill-color', '#006967'); 

                        map.setPaintProperty(layer.id, 'fill-opacity', 0.5); 

                }); 

                }); 

                markersOnTheMap.push(polygonMarker); 

                    polygonMarker.togglePopup(); 

            }); 

        } 
function cleanMap() { 

            Object.keys(layersOnTheMap).forEach(function(layerGroudKey) { 

                layersOnTheMap[layerGroudKey].forEach(function(layer) { 

                    map.removeLayer(layer.id); 

                    map.removeSource(layer.id); 

                }); 

            }); 

            layersOnTheMap = {}; 

            markersOnTheMap.forEach(function(marker) { 

                marker.remove(); 

            }); 

            markersOnTheMap = []; 

        } 
var OriginPoint = {'Origin Point':route.start};			 

        var errorHint = new InfoHint('error', 'bottom-center', 5000).addTo(document.getElementById('map')); 

        var loadingHint = new InfoHint('info', 'bottom-center').addTo(document.getElementById('map')); 

        var layersOnTheMap = {}; 

        var markersOnTheMap = []; 

         

        document.getElementById('submit-button').addEventListener('click', function(e) { 

            e.preventDefault(); 

            errorHint.hide(); 

            loadingHint.setMessage('Loading...'); 

            cleanMap(); 

 

if (markerSelected){ 

OriginPoint = {'Origin Point':[markerSelected._lngLat.lng,markerSelected._lngLat.lat]}; 

}else{ 

OriginPoint = {'Origin Point':[startMarker._lngLat.lng,startMarker._lngLat.lat]}; 

}			 

 

        var serviceData = []; 

serviceData.push({ 

timeBudget: {time: document.getElementById('timebudget').value, color: "#006967"}, 

origin: OriginPoint['Origin Point'], 

location: "Origin Point" 

}); 

 

        tt.services.calculateReachableRange({ 

            batchMode: 'sync', 

            key: '1tN8sunxVpQgWhZjVWXLcR6fzIdLzGXZ', 

            batchItems: serviceData.map(function(data) { 

                return { 

                    timeBudgetInSec: data.timeBudget.time, 

                    origin: data.origin 

                }; 

            }) 

        }).then(function(response) { 

            handleServiceResponse(serviceData, response); 

            loadingHint.hide(); 

        }).catch(function() { 

            loadingHint.hide(); 

            errorHint.setMessage('There was an error with the request, please try again'); 

        }); 

        });
document.getElementById('submit-button-clear').addEventListener('click', function(e) { 

            e.preventDefault(); 

cleanMap(); 

});
              
            
!
999px

Console