Create a route in Google Maps V3 [duplicate]

0

How do I adapt the script below to the following purpose:

The user opens the page and the map appears in a predefined place (company). He then clicks on an input and enters his location, (the input is above the map), then he clicks a "reach" button, and at the same time, a route is drawn from the point where it is, to the place it was pre-defined previously. (eg a company).

**Segue o código:**
 <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Traçar Rota</title>

        <style>

            * { margin: 0; padding: 0; border: 0 }

            #mapa { 
                width: 940px;
                height: 400px;
                border: 10px solid #ccc;;
                margin-bottom: 20px;
            }

            /* =============== Estilos do autocomplete =============== */
            .ui-autocomplete { 
                background: #fff; 
                border-top: 1px solid #ccc;
                cursor: pointer; 
                font: 15px 'Open Sans',Arial;
                margin-left: 3px;
                position: fixed;
            }

            .ui-autocomplete .ui-menu-item { 
                list-style: none outside none;
                padding: 7px 0 9px 10px;
            }

            .ui-autocomplete .ui-menu-item:hover { background: #eee }

            .ui-autocomplete .ui-corner-all { 
                color: #666 !important;
                display: block;
            }

        </style>

        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script><scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>        
        <script type="text/javascript" src="http://www.princiweb.com.br/demos/google-maps-api-v3-busca-endereco-autocomplete/jquery-ui.custom.min.js"></script><script>vargeocoder;varmap;varmarker;vardirectionsService=newgoogle.maps.DirectionsService();functioninitialize(){varlatlng=newgoogle.maps.LatLng(-18.898123,-48.265920);varoptions={zoom:15,center:latlng,mapTypeIds:[google.maps.MapTypeId.ROADMAP,'map_style']};map=newgoogle.maps.Map(document.getElementById("mapa"), options);

            geocoder = new google.maps.Geocoder();

            marker = new google.maps.Marker({
                map: map,
                draggable: false,
                animation: google.maps.Animation.DROP
            });

            marker.setPosition(latlng);

            var styles = [
            {
              stylers: [
                { hue: "#41a7d5" },
                { saturation: 60 },
                { lightness: -20 },
                { gamma: 1.51 }
              ]
            },
            {
              featureType: "road",
              elementType: "geometry",
              stylers: [
                { lightness: 100 },
                { visibility: "simplified" }
              ]
            },
            {
              featureType: "road",
              elementType: "labels"
            }
            ];

            // crio um objeto passando o array de estilos (styles) e definindo um nome para ele;
            var styledMap = new google.maps.StyledMapType(styles, {
            name: "Mapa Style"
            });

            // Aplicando as configurações do mapa
            map.mapTypes.set('map_style', styledMap);
            map.setMapTypeId('map_style');

        }

        $(document).ready(function () {

            initialize();

                // CARREGANDO O MAPA
                function carregarNoMapa(endereco) {
                    geocoder.geocode({ 'address': endereco + ', Brasil', 'region': 'BR' }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {
                                var latitude = results[0].geometry.location.lat();
                                var longitude = results[0].geometry.location.lng();

                                $('#txtEndereco').val(results[0].formatted_address);
                                $('#txtLatitude').val(latitude);
                                $('#txtLongitude').val(longitude);

                                var location = new google.maps.LatLng(latitude, longitude);
                                marker.setPosition(location);
                                map.setCenter(location);
                                map.setZoom(16);
                            }
                        }
                    })
                }

                // CAPTURANDO AS POSIÇÕES E RESULTANDO
                google.maps.event.addListener(marker, 'drag', function () {
                    geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {  
                                $('#txtEndereco').val(results[0].formatted_address);
                                $('#txtLatitude').val(marker.getPosition().lat());
                                $('#txtLongitude').val(marker.getPosition().lng());
                            }
                        }
                    });
                });

                $("#txtEndereco").autocomplete({
                    source: function (request, response) {
                        geocoder.geocode({ 'address': request.term + ', Brasil', 'region': 'BR' }, function (results, status) {
                            response($.map(results, function (item) {
                                return {
                                    label: item.formatted_address,
                                    value: item.formatted_address,
                                    latitude: item.geometry.location.lat(),
                                    longitude: item.geometry.location.lng()
                                }
                            }));
                        })
                    },
                    select: function (event, ui) {
                        $("#txtLatitude").val(ui.item.latitude);
                        $("#txtLongitude").val(ui.item.longitude);
                        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
                        marker.setPosition(location);
                        map.setCenter(location);
                        map.setZoom(16);
                    }
                });

                 $("#btnEndereco").click(function(){
                    var directionsDisplay = new google.maps.DirectionsRenderer();
                    var request = {
                        origin: $("#txtEndereco").val(),
                        destination: marker.position,
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    };

                    directionsService.route(request, function(response, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            directionsDisplay.setDirections(response);
                            directionsDisplay.setMap(map);
                        }
                    });
                });

                $("form").submit(function(event) {
                    event.preventDefault();

                    var endereco = $("#txtEndereco").val();
                    var latitude = $("#txtLatitude").val();
                    var longitude = $("#txtLongitude").val();

                    alert("Endereço: " + endereco + "\nLatitude: " + latitude + "\nLongitude: " + longitude);
                });

        });


    </script>

</head>

<body>      

    <form method="post" action="">    
                <fieldset>   

                    <div class="campos" style="margin: 15px;">
                        <input type="text" id="txtEndereco" name="txtEndereco" size="50" style="padding: 15px; border: 1px solid #cdcdcd;" placeholder="Onde estou..."/>
                        <input type="button" id="btnEndereco" name="btnEndereco" value="CHEGAR" style=" padding: 15px;" />
                    </div>

                    <div id="mapa"></div>

                    <input type="hidden" type="submit" value="Enviar" name="btnEnviar" />

                    <input type="hidden" id="txtLatitude" name="txtLatitude" />
                    <input type="hidden" id="txtLongitude" name="txtLongitude" />

                </fieldset>
    </form>

</body>
</html>
    
asked by anonymous 28.04.2015 / 20:00

1 answer

1

First you need the service DirectionsService , this you can put next to the variables that are at the top of your script :

var directionsService = new google.maps.DirectionsService();

And then, on the click of the btnEndereco button, you can substitute for the call of this service that consists of starting the object to render the directions, creating an object with the necessary parameters to carry out the request and actually doing it:

var directionsDisplay = new google.maps.DirectionsRenderer();

var request = {
        origin: $("#txtEndereco").val(),
        destination: marker.position,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            directionsDisplay.setMap(map);
        }
});

After completing the request successfully, the route will be drawn on the map. More information about this solution can be found in documentation of this service.

    
28.04.2015 / 20:21