Create a route in Google Maps V3

Asked

Viewed 3,550 times

1

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

The user opens the page and appears the map in a predefined place (company). Then he clicks on an input and enters its location, (the input is above the map), then he clicks on a "get" button, and at the same moment, a route is drawn from the point where it is, to the place that was already predefined previously. (ex: 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>
        <script src="//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>

        var geocoder;
        var map;
        var marker;
        var directionsService = new google.maps.DirectionsService();

        function initialize() {
            var latlng = new google.maps.LatLng(-18.898123, -48.265920);
            var options = {
                zoom: 15,
                center: latlng,
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
            };

            map = new google.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>
  • you edited the answer and asked to reopen the question using code provided in a reply. What you are doing is not correct. If you really want the issue to be reopened, rephrase the issue by providing more data than you intend to do, what is missing and what is going wrong.

1 answer

3


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

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

And then, at the click of the button btnEndereco, you can override by the call of this service consisting of starting the rendering object of the directions, creating an object with the parameters necessary to perform the request and actually performing 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 successfully completing the request, the route will be drawn on the map. In the documentation of this service you find more information, if you want more details of this solution.

  • Paulo Rodrigues, I updated the code. Why isn’t it working?

  • His method createrote() may not be called in the onclick of <input> directly. Place it inside the $("#btnEndereco").click(function() {.

  • Paulo Rodrigues, I made the changes but the map is not showing....

  • Syntax error, failed to close } and ). And you call the double-click function. Here a well-formatted code, I just commented on the autocomplete that you can come back later.

  • Paulo, I realized exactly how you passed me. See how the script looked, I updated here. When I set the route, it kind of "bug", see the script... Hugs

  • Here there is no bug. If you use the autocomplete, select an address it will put the pin on the map and press the button the route will be made from the address of the pin to the address of the text box, which will be the same. If you need a fixed point of origin, put it in the parameter destination in the code above.

  • Like, the code has evolved enough. But the idea is that when the user opens the map, it will already be at a specific point, in this case, a company. After he enters the location where he is and selects it, the map will show the Marketer from where he is and a route will be drawn from where he is to the company that was previously placed. That is, one Marker will stay where I am, and the other will stay at the preset place, and the route is drawn between them after the user selects the address from where he is.

  • As I said, the parameter destination then it should be changed to a fixed address, which is the address of the company you refer to.

  • How can I enter the address I want in this Destination parameter? I’ve been tinkering with the api for a while now...

  • It’s a string: destination: "rua tal, 12, uberlandia"

  • Yes, it is with this path "Destination: Marker.position", precise takes it to a specific latitude. As ex: (-18.898123, -48.265920);

  • The same way you initialize the map with a specific point. Use new google.maps.LatLng(-18.898123, -48.265920);.

  • I understand. Now it works. However, when I type in my address it is already setting my new location automatically. I want him to do the search only after I click on the "get" button. But that during the period that I am still typing the address, it continues in the preset place, understood?

  • Where the autocomplete, you have source and select. Remove the execution of select.

  • Thank you so much ! It worked perfectly, you’re great, man! Another thing, when performing the search it is showing two points (A and B) of routes, but earlier, I put a custom symbol, and when the routes are shown, they are on top. As in the image: http://www.tickimg.com.br/uploads/_rota.png . How do I customize the same icon for the two routes, and "vanish" with route icons A and B. Or customize one for route A and another for route B?

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.