Ir ao conteúdo
  • Cadastre-se

Javascript Como pegar valores automaticamente, multiplicar e imprimir na página


Posts recomendados

Olá galera, tenho uma dúvida para me ajudarem quem souber, tenho um código de um mapa do google maps com origem e destino já setados por padrão, a pessoa coloca apenas os waypoints, então ele retorna as distâncias de um ponto até no outro, rota 1, rota 2 e rota 3, mas eu preciso calcular o valor total das 3 rotas, partida e chegada, e imprimir na tela este valor, por fim multiplicar automaticamente o resultado por R$0,75 e também por R$1,50 e imprimir na tela dizendo valor total, por exemplo se a distância total das 3 rotas forem 300Km, então seria 300Km X R$1,50 = R$450,00 e assim para R$0,75 também, alguem pode me ajudar?  Segue o código completo abaixo, lembrando que precisa colocar a KEY no fim do código para poder fazer consulta e testar, porque o google coloca limite de consultas então cada KEY pode fazer uma determinada quantidade de consultas por dia, se poderem adicionar no código apenas o que preciso agreço desde já.

<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Waypoints in directions</title>
    <style>
        #right-panel {
            font-family: 'Roboto','sans-serif';
            line-height: 30px;
            padding-left: 10px;
        }

            #right-panel select, #right-panel input {
                font-size: 15px;
            }

            #right-panel select {
                width: 100%;
            }

            #right-panel i {
                font-size: 12px;
            }

        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #map {
            height: 100%;
            float: left;
            width: 70%;
            height: 100%;
        }

        #right-panel {
            margin: 20px;
            border-width: 2px;
            width: 20%;
            height: 400px;
            float: left;
            text-align: left;
            padding-top: 0;
        }

        #directions-panel {
            margin-top: 10px;
            background-color: #FFEE77;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <div id="right-panel">
        <div>
          <p><b>Calcular valor do frete</b>
            <br>
            <i>Digite o nome da rua ou CEP de Partida e Chegada</i>
            <br>
           Partida <br>
           <input id="Text1" type="text" value=""" /><br>
           Chegada<br>
            <input id="Text2" type="text" value="" />
              
            <br>
              
            <br>
            <input type="submit" id="submit" value="Calcular">
           </p>
        </div>
        <div id="directions-panel"></div>
    </div>
    <script>
        function initMap() {
            var directionsService = new google.maps.DirectionsService;
            var directionsDisplay = new google.maps.DirectionsRenderer;
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 6,
                center: { lat: -26.453258, lng: -49.045733 }
            });
            directionsDisplay.setMap(map);

            document.getElementById('submit').addEventListener('click', function () {
                calculateAndDisplayRoute(directionsService, directionsDisplay);
            });
        }

        function calculateAndDisplayRoute(directionsService, directionsDisplay) {
            var waypts = [];
            var textbox1 = document.getElementById('Text1');
            var textbox2 = document.getElementById('Text2');

            if (textbox1.value != "") {
                waypts.push({
                    location: textbox1.value,
                    stopover: true
                });
            }
            if (textbox2.value != "") {
                waypts.push({
                    location: textbox2.value,
                    stopover: true
                });
            }

            //var checkboxArray = document.getElementById('waypoints');
            //for (var i = 0; i < checkboxArray.length; i++) {
            //    if (checkboxArray.options[i].selected) {
            //        waypts.push({
            //            location: checkboxArray[i].value,
            //            stopover: true
            //        });
            //    }
            //}

 

            directionsService.route({
                origin: "Manoel Francisco da Costa",
                destination: "Manoel Francisco da Costa",
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: 'DRIVING'
            }, function (response, status) {
                if (status === 'OK') {
                    directionsDisplay.setDirections(response);
                    var route = response.routes[0];
                    var summaryPanel = document.getElementById('directions-panel');
                    summaryPanel.innerHTML = '';
                    // For each route, display summary information.
                    for (var i = 0; i < route.legs.length; i++) {
                        var routeSegment = i + 1;
                        summaryPanel.innerHTML += '<b>Rota: ' + routeSegment +
                            '</b><br>';
                        summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
                        summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
                        summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
                    }
                } else {
                    window.alert('Directions request failed due to ' + status);
                }
            });
        }
       
    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=SUA-KEY-AQUI_8&callback=initMap">
    </script>
</body>
</html>

 

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...