I am working on a project where I need to obtain all the coordinate points along a walking route between two specified addresses (source and destination) using the Google Maps API. When using the Google Maps website in walking mode, a blue circle marks the walking path, as illustrated in the image below. I am looking for the function that can replicate this via the API.
Could someone guide me on which function or method in the Google Maps API can be used to achieve this? Any example code or references to the relevant API documentation would be really appreciated.
enter image description here
I have implemented this code, but is not possible to get the same result.
<script>
let map;
let directionsService;
let directionsRenderer;
function initMap() {
// Inicializa o mapa
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -23.086325716360644, lng: -47.23343424756318 }, // Coordenadas de São Paulo
zoom: 15,
});
// Cria os serviços do Google Maps
directionsService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer();
// Configura o directionsRenderer para usar o mapa criado
directionsRenderer.setMap(map);
// Chama a função para calcular a rota
calculateAndDisplayRoute();
}
function calculateAndDisplayRoute() {
directionsService.route({
origin: { lat: -23.088191066799215, lng: -47.24902903973025 }, // Ponto de partida
destination: { lat: -23.086296107502847, lng: -47.228423881389276 }, // Ponto de chegada
travelMode: google.maps.TravelMode.WALKING,
}, (response, status) => {
if (status === 'OK') {
directionsRenderer.setDirections(response);
placeIntermediateMarkers(response);
} else {
window.alert('Falha ao calcular a rota: ' + status);
}
});
}
function placeIntermediateMarkers(directionsResult) {
const route = directionsResult.routes[0];
const stepDistance = 5; // Distância desejada entre os pontos, em metros
let distanceAccumulated = 0;
let lastPosition = route.overview_path[0]; // Inicialmente, o último ponto é o ponto de origem
// Criar um marcador no início
new google.maps.Marker({
position: lastPosition,
map: map,
title: `Start - ${lastPosition.toString()}`
});
console.log(lastPosition.toString())
// Iterar sobre os pontos da rota para criar marcadores a cada 40 metros
route.overview_path.forEach((currentPosition, index) => {
if (index === 0) {
return; // Pula o primeiro ponto, já que é o ponto de origem
}
console.log(currentPosition.toString())
const segmentDistance = google.maps.geometry.spherical.computeDistanceBetween(lastPosition, currentPosition);
distanceAccumulated += segmentDistance;
while (distanceAccumulated >= stepDistance) {
const excessDistance = distanceAccumulated - stepDistance;
const moveBackDistance = segmentDistance - excessDistance;
// Calcular a posição proporcional do marcador ao longo do segmento atual
const intermediatePosition = google.maps.geometry.spherical.interpolate(lastPosition, currentPosition, moveBackDistance / segmentDistance);
// Criar marcador
new google.maps.Marker({
position: intermediatePosition,
map: map,
title: `${intermediatePosition.toString()} ${Math.round((stepDistance - excessDistance) + (stepDistance * Math.floor(distanceAccumulated / stepDistance)))}m`
});
// Atualizar lastPosition para a posição do último marcador e ajustar o acumulado
lastPosition = intermediatePosition;
distanceAccumulated = excessDistance;
}
});
// Criar um marcador no fim
new google.maps.Marker({
position: route.overview_path[route.overview_path.length - 1],
map: map,
title: `End - ${route.overview_path[route.overview_path.length - 1].toString()}`
});
}
</script>
[enter image description here](https://i.sstatic.net/Z4eQNoRm.png)
rbarrozo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.