Monday, September 26, 2011

Creating Google Map with multiple way points and draggable directions using asp.net and java script

//This code is for Creating Google Map with multiple way points and draggable directions using asp.net and java script. Please set design according to your css//

<head id="Head1" runat="server">
     <title>Calculate distance</title>
 
    <script src="http://maps.google.com/maps/api/js?sensor=false&amp;key=ABQIAAAAJBjl1Th9QFwMQaJjFDBKahS_UYXK4NsaVm1AC7JD1mYvEQ3NmBRS7MuG9QhvC79P5JUmScpoMMAI8Q"
        type="text/javascript"></script>

    <script type="text/javascript">

        function showInformation() {
            var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
            var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
            document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Calculate Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + document.getElementById('txtDistance').value + ' kilometers)';
        }

        function showLocation() {
            geocoder.getLocations(document.forms[0].fromAddress.value, function(response) {
                if (!response || response.Status.code != 200) {
                    alert("Sorry, we were unable to geocode the first address");
                }
                else {
                    location1 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
                    geocoder.getLocations(document.forms[0].toAddress.value, function(response) {
                        if (!response || response.Status.code != 200) {
                            alert("Sorry, we were unable to geocode the second address");
                        }
                        else {
                            location2 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
                            gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                        }
                    });
                }
            });
        }



        var finalToAddress = "";
        var address = 'India'; //Default map location on page load
        var rendererOptions = {
            draggable: true
        };
        var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
        var directionsService = new google.maps.DirectionsService();
        var map;
        var mygc = new google.maps.Geocoder();
        mygc.geocode({ 'address': address },

         function(results, status) {
             var country1 = results[0].geometry.location.lat();
             var country2 = results[0].geometry.location.lng();
             var australia = new google.maps.LatLng(country1, country2);
             initialize(australia);
         }
        );

        function initialize(australia) {
            var myOptions =
    {
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: australia
    };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById("directionsPanel"));
            google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {


                computeTotalDistance(directionsDisplay.directions);
            });
            calcRoute();

        }

        function calcRoute(fromAddress, toAddress) {
            var items = new Array();
            for (var i = 1; i <= textboxes; i++) {
                items[(i - 1)] = document.getElementById(i.toString()).value;
            }
            var waypoints = [];
            var address;
            address = document.getElementById('toAddress').value;

            if (items.length > 0) {
                waypoints.push({
                    location: address,
                    stopover: true
                })
            };

            for (var i = 0; i < items.length - 1; i++) {
                address = items[i];
                if (address !== "") {

                    waypoints.push({
                        location: address,
                        stopover: true
                    });
                }
            }

            var toAddress1 = "";

            if (waypoints.length != 0) {
                toAddress1 = document.getElementById((waypoints.length).toString()).value;
                finalToAddress = document.getElementById((waypoints.length).toString()).value;

            }
            else {
                toAddress1 = document.getElementById('toAddress').value;
                finalToAddress = document.getElementById('toAddress').value;


            }


            var request = {
                origin: fromAddress,
                destination: toAddress1,

                waypoints: waypoints,

                optimizeWaypoints: false,

                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

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

        function computeTotalDistance(result) {
            var total = 0;

            var myroute = result.routes[0];

            for (i = 0; i < myroute.legs.length; i++) {
                total += myroute.legs[i].distance.value;

            }

            total = parseFloat(Math.round((total / 1000) * 100) / 100);
            var measurUnit = 'KM'; //set unit of distance according to you
            if (measurUnit == "KM") {
                document.getElementById('txtDistance').value = total;
                document.getElementById('lblType').innerHTML = "KM";
            }
            else {
                document.getElementById('txtDistance').value = parseFloat(Math.round(((total * 1000) / 1609.344) * 100) / 100);
                document.getElementById('lblType').innerHTML = "Miles";
            }
        }
        function setDirections(fromAddress, toAddress) {
            calcRoute(fromAddress, toAddress);
        }


        /*Functions for adding and removing text boxes*/
        var intTextBox = 0;
        var textboxes = 0;

        function addElement() {
            intTextBox = intTextBox + 1;
            var contentID = document.getElementById('content');
            var newTBDiv = document.createElement('div');
            newTBDiv.setAttribute('id', 'strText' + intTextBox);
            newTBDiv.innerHTML = String.fromCharCode(64 + (intTextBox + 2)) + ' :' + "<input style='margin-top:5px;margin-left:30px;' class='txt3_double' type='text' id='" + intTextBox + "' name='" + intTextBox + "'/>";
            contentID.appendChild(newTBDiv);
            textboxes = intTextBox;
        }


        function removeElement() {
            if (intTextBox != 0) {
                var contentID = document.getElementById('content');
                contentID.removeChild(document.getElementById('strText' + intTextBox));
                intTextBox = intTextBox - 1;
                textboxes = intTextBox;
            }
        }
                
      
        
        
    </script>

</head>
<body onload="initialize()">
    <form id="Form1" runat="server" action="#" onsubmit="setDirections(this.from.value, this.to.value);return false "
    style="margin-left: 20px; text-align: center; overflow: hidden;">
    <div style="min-height: 325px; min-width: 500px; overflow: hidden; vertical-align: middle;">
        <div>
            <div>
                <b>Calculate Distance</b></div>
            <div>
                <div>
                    A :
                    <div>
                        <input type="text" size="25" id="fromAddress" name="from" />
                        <asp:HiddenField ID="hdnDefault" runat="server" />
                    </div>
                </div>
                <div>
                    <div>
                        B :
                        <div>
                            <input type="text" size="25" id="toAddress" name="to" class="txt3_double" />
                        </div>
                        <div>
                        </div>
                        <div id="content">
                        </div>
                    </div>
                    <div>
                        <div>
                            <div>
                                <a href="javascript:addElement();">Add Destination</a> <a href="javascript:removeElement();">
                                    Remove</a>
                            </div>
                        </div>
                        <div>
                            Distance:
                            <div class="nameValueBox fl ">
                                <asp:TextBox ID="txtDistance" runat="server" Enabled="false" CssClass="txt3_double"></asp:TextBox>
                                <asp:Label ID="lblType" runat="server" Text=""></asp:Label>
                            </div>
                        </div>
                        <div>
                            <div>
                                <asp:Button ID="ibtnCalculate" runat="server" Text="Calculate" />
                                <asp:Button ID="ibtnDone" runat="server" Text="Insert" OnClientClick="returnToParent()" />
                            </div>
                        </div>
                        <div>
                            <div id="map_canvas" style="width: 430px; height: 450px; margin-right: 10px;">
                            </div>
                        </div>
                        <div>
                            <p id="results">
                            </p>
                        </div>
                    </div>
                    <div id="directionsPanel" style="text-align: right; vertical-align: top;">
                        <p>
                            <span id="total"></span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
    <br />
</body>




No comments:

Post a Comment