Search code examples
mapsdraggablefixed

Google Maps - Fixed source and draggable destination in website


I`m using the API to integrate Google Maps in our website. But we did not met the requirement by using them.

I tried using different options. Our requirement is that - the source is set to fixed location(should not be dragged) and the accurate destination is to be entered in the text area and the end user should have an option to point out the exact location(may be near to the location entered in the destination text area).

calculation of distance and the remaining part is working fine for me. Pointing the exact location in the destination also achieved.

Only thing to be worked on is that fixing the source location(End user should not drag/move the source location).

<script type="text/javascript">
    var source, destination;
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    google.maps.event.addDomListener(window, 'load', function () {
        new google.maps.places.SearchBox(document.getElementById('txtSource'));
        new google.maps.places.SearchBox(document.getElementById('txtDestination'));
        directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
    });

    function GetRoute() { 
        var mapOptions = {
            zoom: 4,
        };
        map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('dvPanel'));

        //*********DIRECTIONS AND ROUTE**********************//
        source = document.getElementById("txtSource").value;
        destination = document.getElementById("txtDestination").value;

        var request = {
            origin: source,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });

        //*********DISTANCE AND DURATION**********************//
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix({
            origins: [source],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
        }, function (response, status) {
            if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                var distance = response.rows[0].elements[0].distance.text;
                var duration = response.rows[0].elements[0].duration.text;
                var dvDistance = document.getElementById("dvDistance");
                dvDistance.innerHTML = "";
                dvDistance.innerHTML += "Distance: " + distance + "<br />";
                dvDistance.innerHTML += "Duration:" + duration;

            } else {
                alert("Unable to find the distance via road.");
            }
        });
    }
</script>

By using above code, Both the source and destination are draggable.


Solution

  • <script type="text/javascript">
    
        google.maps.event.addDomListener(window, 'load', function () {
            new google.maps.places.SearchBox(document.getElementById('txtSource'));
            new google.maps.places.SearchBox(document.getElementById('txtDestination'));
        });
    
        var gmarkers = [];
        var map = null;
        var startLocation = null;
        var endLocation = null;
        var directionsService = null;
        var polyline = new google.maps.Polyline({
            path: [],
            strokeColor: '#FF0000',
            strokeWeight: 3
        });
    
        function initialize() {
            map = new google.maps.Map(document.getElementById('map_canvas'), {
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            //google.maps.event.addListener(map, 'click', function () {
            //    infowindow.close();
            //});
    
            directionsService = new google.maps.DirectionsService();
            var request = {
                origin: document.getElementById("txtSource").value,
                destination: document.getElementById("txtDestination").value,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsService.route(request, RenderCustomDirections);
        }
    
        function RenderCustomDirections(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                var bounds = new google.maps.LatLngBounds();
                var route = response.routes[0];
                var summaryPanel = document.getElementById("directions_panel");
                startLocation = new Object();
                endLocation = new Object();
    
                summaryPanel.innerHTML = "";
    
                // For each route, display summary information.
                for (var i = 0; i < route.legs.length; i++) {
                    var routeSegment = i + 1;
                    summaryPanel.innerHTML += route.legs[i].start_address + "<br />" + " to " + "<br />";
                    summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
                    summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
                }
    
                var path = response.routes[0].overview_path;
                var legs = response.routes[0].legs;
                for (i = 0; i < legs.length; i++) {
                    if (i == 0) {
                        startLocation.latlng = legs[i].start_location;
                        startLocation.address = legs[i].start_address;
                        startLocation.marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green", false);
                    }
                    endLocation.latlng = legs[i].end_location;
                    endLocation.address = legs[i].end_address;
                    var steps = legs[i].steps;
                    for (j = 0; j < steps.length; j++) {
                        var nextSegment = steps[j].path;
                        var dist_dur = "";
                        if (steps[j].distance && steps[j].distance.text) dist_dur += "&nbsp;" + steps[j].distance.text;
                        if (steps[j].duration && steps[j].duration.text) dist_dur += "&nbsp;" + steps[j].duration.text;
                        for (k = 0; k < nextSegment.length; k++) {
                            polyline.getPath().push(nextSegment[k]);
                            bounds.extend(nextSegment[k]);
                        }
                    }
                }
    
                polyline.setMap(map);
                map.fitBounds(bounds);
                endLocation.marker = createMarker(endLocation.latlng, "end", endLocation.address, "red", true);
    
            }
            else alert("Please try again " + status);
        }
    
        function createMarker(latlng, label, html, color, draggable) {
            //alert("createMarker(" + latlng + "," + label + "," + html + "," + color + ")");
            var contentString = '<b>' + label + '</b><br>' + html;
            var marker = new google.maps.Marker({
                position: latlng,
                draggable: draggable,
                map: map,
            });
    
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.setContent(contentString);
                infowindow.open(map, marker);
            });
            google.maps.event.addListener(marker, 'dragend', function () {
                var request = {
                    origin: startLocation.marker.getPosition(),
                    destination: endLocation.marker.getPosition(),
                    travelMode: google.maps.DirectionsTravelMode.WALKING
                };
                startLocation.marker.setMap(null);
                endLocation.marker.setMap(null);
    
                gmarkers = [];
                polyline.setMap(null);
                polyline = new google.maps.Polyline({
                    path: [],
                    strokeColor: '#FF0000',
                    strokeWeight: 3
                });
                directionsService.route(request, RenderCustomDirections);
            });
            return marker;
        }
    
    </script>