medk
medk

Reputation: 9549

Changing JavaScript to jQuery not working

I found this tutorial about adding a map that calculates the distance between two positions. It works great. The problem here is that it's written in raw JavaScript, not jQuery.

When I include jQuery and change for example "document.getElementById('txtSource')" by "$('#txtSource')" it won't work.

Here is the original code: http://pastebin.com/BKqgYWEw

Here is my edited code: http://pastebin.com/ZrK7cSAb

Any suggestions here?

Thanks.

Upvotes: 0

Views: 62

Answers (2)

n0m4d
n0m4d

Reputation: 832

It's like @ssube said: You were passing a jquery object not a DOM node. I tried to accomplish what you wanted by traversing the DOM with JQuery objects and also passing the right DOM node elements to the API. Please refer to the working solution below:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
    <script>
        var source, destination;
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        google.maps.event.addDomListener(window, 'load', function () {
            new google.maps.places.SearchBox($('#txtSource').get(0));
            new google.maps.places.SearchBox($('#txtDestination').get(0));
            directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
        });

        function GetRoute() {
            var mumbai = new google.maps.LatLng(18.9750, 72.8258);
            var mapOptions = {
                zoom: 7,
                center: mumbai
            };
            map = new google.maps.Map($('#dvMap').get(0), mapOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel($('#dvPanel').get(0));

            //*********DIRECTIONS AND ROUTE**********************//
            source = $('#txtSource').val();
            destination = $('#txtDestination').val();

            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 = $('#dvDistance');
                    dvDistance.html('');
                    dvDistance.html('Distance: ' + distance + '<br>');
                    dvDistance.html('Duration:' + duration);

                } else {
                    alert('Unable to find the distance via road.');
                }
            });
        }
    </script>
    <table border="0" cellpadding="0" cellspacing="3">
        <tr>
            <td colspan="2">
                Source:
                <input type="text" id="txtSource" value="Bandra, Mumbai, India" style="width: 200px" />
                &nbsp; Destination:
                <input type="text" id="txtDestination" value="Andheri, Mumbai, India" style="width: 200px" />
                <br />
                <input type="button" value="Get Route" onclick="GetRoute()" />
                <hr />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <div id="dvDistance">
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div id="dvMap" style="width: 500px; height: 500px">
                </div>
            </td>
            <td>
                <div id="dvPanel" style="width: 500px; height: 500px">
                </div>
            </td>
        </tr>
    </table>
    <br />
</body>
</html>

Upvotes: 1

ssube
ssube

Reputation: 48317

jQuery selectors and DOM elements are not the same thing. You simply can't pass a selector like that. However, you can fetch the element from the selector using the get method.

console.log(document.getElementById('test').constructor, $('#test').constructor, $('#test').get(0).constructor);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

Upvotes: 0

Related Questions