For my internship, I’m currently working on creating a route planner. I’m utilizing OpenRoute Service and Leaflet for this project. While I can generate a route successfully, I encounter a funny issue when trying to display the route on a map—it appears in the ocean! I’ve attempted to resolve this by providing center coordinates and potentially a boundary box (bbx). What am I doing wrong here, and can someone assist me?
function calculateRoute() {
extractAndConvertToCoordinates().then(() => {
let coordinatesArray = [];
if (startPointCoordinates.length === 0) {
getStartPointCoordinates(sPostcode, sStraatnaam, sHuisnummer).then((startPointCoordinates) => {
coordinatesArray.push(startPointCoordinates);
coordinatesArray.push.apply(coordinatesArray, tableCoordinates);
if (endPointCoordinates && endPointCoordinates.length !== 0) {
coordinatesArray.push(endPointCoordinates);
}
sendRequest(coordinatesArray);
}).catch(error => {
console.error('Error fetching start point coordinates:', error);
});
} else {
coordinatesArray.push(startPointCoordinates);
coordinatesArray.push.apply(coordinatesArray, tableCoordinates);
if (endPointCoordinates && endPointCoordinates.length !== 0) {
coordinatesArray.push(endPointCoordinates);
}
sendRequest(coordinatesArray);
}
});
}
function sendRequest(coordinatesArray) {
let requestBody = {
coordinates: coordinatesArray
};
let request = new XMLHttpRequest();
let transport = document.getElementById('SelectedVehicle').value;
request.open('POST', 'https://api.openrouteservice.org/v2/directions/' + transport + '/geojson');
request.setRequestHeader('Accept', 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', api);
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
let routeData = JSON.parse(this.responseText);
let routeCoordinates = routeData.features[0].geometry.coordinates;
let centerCoordinates = [52.1326, 5.2913]; // Netherlands center coordinates
let map = L.map('map').setView(centerCoordinates, 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.polyline(routeCoordinates, { color: 'green' }).addTo(map);
map.fitBounds(L.polyline(routeCoordinates).getBounds());
}
};
request.send(JSON.stringify(requestBody));
}