1

Estoy intentando hacer un google map que marque una ruta con varios puntos, ya vi un ejemplo en la página de google maps. Para hacerlo necesito un array con las posiciones intermedias. Yo tengo las posiciones en una bd mysql pero no se como pasar las direcciones al javascript.

Este es el RutaCompleta.jsp (no se si se puede hacer eso del c:foreach con <script>)

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Ruta Completa</title>
        <link href="repartidores/css/mapa.css" rel="stylesheet" type="text/css"/>
        <script src="repartidores/js/mapaRutaCompleta.js" type="text/javascript"/>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBnGP5-NeoiUKVYrv32QL7ydnM3ji4NIro&callback=initMap"
        async defer></script>
        <c:forEach items="${repartos}" var="reparto">
            <script type="text/javascript">
                waypoints.push({
                    location: '${reparto.pedido.direccion}',
                    stopover: true
                });
            </script>
        </c:forEach>
    </head>
    <body>
        <div id="map">

        </div>
    </body>
</html>

mapaRutaCompleta.js

var posActualLng = 0;
var posActualLat = 0;
var waypoints = [];

function obtenerUbicacion(){
    if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(position) {
            posActualLat = position.coords.latitude;
            posActualLng = position.coords.longitude;

        }, function() {
            alert("Error");
        });
    } 
    else {
        // El navegador no soporta Geolocation
        alert("El navegador no soporta geolocation");
    }
}



// MOSTRAR MAPA
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: posActualLat, lng: posActualLng}
    });

    directionsDisplay.setMap(map);
    calculateAndDisplayRoute(directionsService, directionsDisplay);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {

  directionsService.route({
    origin: {lat: -34.378522, lng: -55.234380},
    destination: {lat: -34.880044, lng: -56.078461},
    waypoints: waypoints,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else {
      alert('Directions request failed due to ' + status);
    }
  });
}

RutaCompletaServlet.java

@WebServlet(name = "RutaCompletaServlet", urlPatterns = {"/RutaCompletaServlet"})
public class RutaCompletaServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Consulta cons, cons1, cons2;
    try {
        cons = new Consulta("r.id, idRepartidor, idPedido, tiempo", "repartos r, pedidos p");
        cons1 = new Consulta("*", "pedidos");
        cons2 = new Consulta("*", "usuarios");
        ResultSet rs = cons.recuperar("idRepartidor = 11 and r.idPedido = p.id and p.estado <> 'ENTREGADO'");
        List<Repartos> repartos = new ArrayList<>();
        // recorro el rs con los repartos
        while (rs.next()){
            int idPed = rs.getInt("idPedido");
            ResultSet rs1 = cons1.recuperarPorId(idPed);
            // recorro el rs1 con los pedidos
            while(rs1.next()){
                Pedido pedido = new Pedido(rs1.getInt("id"), rs1.getString("descripcion"), rs1.getInt("precio"), rs1.getString("direccion"), rs1.getString("fechaHora"), rs1.getString("comentario"), rs1.getString("estado"));

                ResultSet rs2 = cons2.recuperarPorId(rs.getInt("idRepartidor"));
                // recorro el rs2 con los usuarios
                while (rs2.next()){
                    Usuario repartidor = new Usuario(rs2.getInt("documento"), rs2.getString("nombre"), rs2.getString("apellido"), rs2.getString("domicilio"), rs2.getString("telefono"), rs2.getString("nomUsuario"), rs2.getString("password"), rs2.getString("rol"));
                    Repartos rep = new Repartos(rs.getInt("id"), repartidor, pedido);
                    repartos.add(rep);
                }                  
            }
        }

        request.setAttribute("repartos", repartos);
        request.getRequestDispatcher("/repartidores/RutaCompleta.jsp").forward(request, response);

    } catch (SQLException | ClassNotFoundException ex) {
        Logger.getLogger(ConsultaPedidosServlet.class.getName()).log(Level.SEVERE, null, ex.getMessage());
    }

}
4
  • cuando termina de cargar la página ¿has comprobado si waypoints tiene elementos? el 21 nov. 2016 a las 7:55
  • No pude, intenté hacer debug pero no me deja. el 21 nov. 2016 a las 14:27
  • Y si invocas el endpoint del servlet "/RutaCompletaServlet"? el 21 nov. 2016 a las 18:10
  • sí, trae los datos bien. el 22 nov. 2016 a las 2:08

1 respuesta 1

1

Creo que el problema que tienes es que quieres que el servidor te monte el html y te ejecute el javascript para construir los datos del mapa. La verdad es que no se si funcionaría pero lo veo una solución muy rebuscada.

Creo que te sería más fácil resolverlo desde javascript directamente. Pintas tu vista con el mapa y desde javascript (ya en el cliente cuando se ha cargado la página) haces una llamada a tu servlet que te devuelve los puntos. Lo recorres y vas pintando lo que necesites.

2
  • Ya pude, tenía mal en el jsp: <script src="repartidores/js/mapaRutaCompleta.js" type="text/javascript"/> lo puse así: <script src="repartidores/js/mapaRutaCompleta.js" type="text/javascript"> </script> y me funcionó. el 26 nov. 2016 a las 3:05
  • Me alegro de que lo hayas resuelto por fin. el 28 nov. 2016 a las 12:57

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.