How to get the points all over the walking path using API Google MAP

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><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>
</code>
<code><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> </code>
<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>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
[enter image description here](https://i.sstatic.net/Z4eQNoRm.png)
</code>
<code> [enter image description here](https://i.sstatic.net/Z4eQNoRm.png) </code>

[enter image description here](https://i.sstatic.net/Z4eQNoRm.png)

New contributor

rbarrozo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật