Display alternative route using Google Map API in ASP.Net

Last Reply 11 months ago By dharmendr

Posted 11 months ago

I want to get all alternate routes from source to destination. Here is my code. From this code, I can get address by hitting API. But somethime it's not working. Is there , any better option for getting all location name from source to destination.

<!DOCTYPE html>
<html>
<body>
    <div>Source Address : <input type="text" id="txtsourceaddress" /></div>
    <div>Destination  Address : <input type="text" id="txtdestinationaddress" /></div>
    <a href="javascript:" class="form-submit" onclick="setvalue();" style=" background-color: #ba68c8;color: #fff;padding:10px 17px;">Submit</a>
    <div id="map" style="width: 400px; height: 300px;"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBZjdHClhks-Lv7MqwY-uihYtJHdXexcXk&callback=myMap"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        function setvalue() {
            var myDate = new Date($("#txtdeparturetime").val());
            var offset = myDate.getTimezoneOffset() * 60 * 1000;
            var withOffset = myDate.getTime();
            var withoutOffset = withOffset - offset;
            $("#hdnsetvalue").val(withOffset);
            var saddress = document.getElementById('txtsourceaddress').value;
            getLatitudeLongitude(showResult, saddress);
            var daddress = document.getElementById('txtdestinationaddress').value;
            getLatitudeLongitude(showdestinationResult, daddress);

            setTimeout(function () { getsetmap(); }, 5000);
        }
    </script>
    <script type="text/javascript">
        google.maps.event.addDomListener(window, 'load', function () {
            var places = new google.maps.places.Autocomplete(document.getElementById('txtsourceaddress'));
            google.maps.event.addListener(places, 'place_changed', function () {
                var place = places.getPlace();
                var address = place.formatted_address;
                var latitude = place.geometry.location.lat();
                var longitude = place.geometry.location.lng();
                var mesg = "Address: " + address;
                mesg += "\nLatitude: " + latitude;
                mesg += "\nLongitude: " + longitude;
                // alert(mesg);
            });
        });

        google.maps.event.addDomListener(window, 'load', function () {
            var places = new google.maps.places.Autocomplete(document.getElementById('txtdestinationaddress'));
            google.maps.event.addListener(places, 'place_changed', function () {
                var place = places.getPlace();
                var address = place.formatted_address;
                var latitude = place.geometry.location.lat();
                var longitude = place.geometry.location.lng();
                var mesg = "Address: " + address;
                mesg += "\nLatitude: " + latitude;
                mesg += "\nLongitude: " + longitude;
                // alert(mesg);
            });
        });

        function getsetmap() {
            var directionsService = new google.maps.DirectionsService();
            var myOptions = {
                zoom: 7,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(document.getElementById("map"), myOptions);
            var sourceaddress = $('#txtsourceaddress').val().split(",");
            var destiaddress = $('#txtdestinationaddress').val().split(",");
            var st = new google.maps.LatLng(sourceaddress[0], sourceaddress[1]);
            var en = new google.maps.LatLng(destiaddress[0], destiaddress[1]);

            var request = {
                origin: st,
                destination: en,
                travelMode: google.maps.DirectionsTravelMode.DRIVING,
                // Returns multiple routes
                provideRouteAlternatives: true
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
             
                    if (response.routes && response.routes.length > 0) {
                        var routes = response.routes;
                        for (var j = 0; j < routes.length; j++) {
                            var dr = new google.maps.DirectionsRenderer();
                            dr.setDirections(response);
                            // Tell the DirectionsRenderer which route to display
                            dr.setRouteIndex(i);
                            dr.setMap(map);
                            var points = routes[j].overview_path;
                       
                            for (var i = 0; i < points.length; i++) {
                                console.log(GetAddress(getLiText(points[i])));
                            }
                        }
                    }
                }
            });
        }
        function getLiText(point) {
            var lat = point.lat(),
                lng = point.lng();
            return  lat + "," + lng;
        }

        function GetAddress(lat, lng) {
            $.ajax({
                url: "/Home.aspx/setaddress",
                type: 'POST',
                data: "{ 'lat': '" + lat + "','lng' : '" + lng +  "'}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    console.log(lat & "," & lng);
                    console.log(data.d);
                    return data.d;
                },
                error: function (result) {
                }
            });   //end of ajax
        }
        function getLatitudeLongitude(callback, address) {

            // If adress is not supplied, use default value 'Ferrol, Galicia, Spain'
            address = address || 'Ferrol, Galicia, Spain';
            // Initialize the Geocoder
            geocoder = new google.maps.Geocoder();
            if (geocoder) {
                geocoder.geocode({
                    'address': address
                }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        callback(results[0]);
                    }
                    else {
                        alert(status);
                    }
                });
            }
        }

        function showResult(result) {
            $('#txtsourceaddress').val(result.geometry.location.lat() + ',' + result.geometry.location.lng());
        }

        function showdestinationResult(result) {
            $('#txtdestinationaddress').val(result.geometry.location.lat() + ',' + result.geometry.location.lng());
        }
    </script>
</body>
</html>

 

    <System.Web.Services.WebMethod()>
    Public Shared Function setaddress(ByVal lat As String, ByVal lng As String) As String
        Dim m_xmld As XmlDocument = New XmlDocument()
        Dim m_nodelist As XmlNodeList
        m_xmld = New XmlDocument()
        m_xmld.Load("https://maps.google.com/maps/api/geocode/xml?latlng=" & lat & "," & lng & "&sensor=false&key=API_Key")
        m_nodelist = m_xmld.SelectNodes("/GeocodeResponse/result")
        Return m_nodelist(0)("formatted_address").InnerText.Trim()
    End Function

 

Posted 11 months ago

I will get back soon.