将javasceript索引转换为子javascript文件

时间:2017-05-22 09:08:05

标签: javascript cordova

我有一个电话间隙应用程序,我正在使用带有java脚本索引文件的phonegap中的其他项目中的子功能,现在我想将子索引文件集成到我的原始项目中,我知道我不能有两个索引文件,因为phonegap应用程序有onsucees和deviceReady函数

我想将此代码转换为常规的Java脚本文件

$("#tourButton").click(function(){
     var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
       // app.receivedEvent('deviceready');
       navigator.geolocation.getCurrentPosition(app.onSuccess, app.onError);
    },

    onSuccess: function(position){
        //My coordinates: Latitude: 21.371479, Longitude: 39.794234
        //var longitude = position.coords.longitude;
        //var latitude = position.coords.latitude;

        var longitude = 39.794234;
        var latitude = 21.371479;

        var latLong = new google.maps.LatLng(latitude, longitude);

        var mapOptions = {
            center: latLong,
            zoom: 9,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        var marker = new google.maps.Marker({
              position: latLong,
              map: map,
              title: 'my location'
        });
        //document.getElementById("jjj").innerHTML=longitude + ", " + latitude;

        var hours = $("input:text").val();
        var radioValue = $("input[name='transport']:checked").val();
        var distanceInKM;
        var serviceURL ;
        var dataArray = [];
        var query ;

        var matches = hours.match(/^\d{1,2}(?:\.\d{1,2})?$|^\.\d{1,2}$/);
        if (hours!="" && !matches){
            alert( " القيمة " + hours + " غير صحيحة .. الرجال ادخال قيمة اخرى (مثال 4 أو 4.5) " );
        }
        else if (!hours.match(/\S/)) {
            alert(" الرجاء تحديد ساعات الفراغ ");
        }
        else if ($("input[type=radio]:checked").length <= 0) {
            alert("الرجاء اختيار وسيلة المواصلات المفضلة");
        }
        else if (hours>0 && radioValue == "DRIVING") { //DRIVING is selected
            distanceInKM = drivingDistanceCal(hours);
            //document.getElementById("mmm").innerHTML = drivingDistanceCal(hours);
            serviceURL = "http://192.168.8.100/maleem/distanceTran.php";
            query = { user: distanceInKM, lat: latitude, lng: longitude };
        }
        else if (hours>0 && radioValue == "WALKING") { //WALKING is selected
            distanceInKM = walkingCalDistanceCal(hours);
            //document.getElementById("mmm").innerHTML = walkingCalDistanceCal(hours);
            serviceURL = "http://192.168.8.100/maleem/distanceTran.php";
            query = { user: distanceInKM, lat: latitude, lng: longitude };
        }
        else{
            alert(" الرجاء تحديد ساعات الفراغ بالإضافة إلى وسيلة المواصلات ");
        }

        function drivingDistanceCal(hours){
            distanceInKM = (45 * hours)/3;
            return distanceInKM;
            //alert(distanceInKM);
        }
        function walkingCalDistanceCal(hours){
            distanceInKM = (4.82803 * hours)/3;
            return distanceInKM;
            //alert(distanceInKM);
        }

        $.getJSON( serviceURL,query)
        .done(function( data ) {
            if(data.items == "no data"){
              alert("عذراً لا توجد نتائج");
            }
            else{
                $.each( data.items, function( i, item ) {
                dataArray.push([item.L_ID , item.Lat , item.Lon , item.Description ,item.Image , item.Title, item.Type_ID, ]);
            });

            //document.getElementById("mmm").innerHTML = dataArray.length;
            //document.getElementById("result1").innerHTML = dataArray[1][1] + ", " + dataArray[1][2];


            document.getElementById("back").style.display = 'block'; 

            var button;
            var content = document.getElementById("content");                  


            for(var i = 0 ; i < dataArray.length; i++){
                var table = document.getElementById("table");
                var row = table.insertRow(0);

                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);

                cell1.innerHTML = dataArray[i][5];
                //cell2.innerHTML = dataArray[i][0];

                var btn = document.createElement("BUTTON");
                var t = document.createTextNode("اختر");
                btn.appendChild(t);
                btn.setAttribute("id",dataArray[i][0]);
                cell2.appendChild(btn);

                var tempArray = dataArray[i];             

                btn.onclick = (function(tempArray) { 
                    return function() {
                        corefunction(tempArray);
                    }; 
                }(dataArray[i]));

            }

            function corefunction(tempArray){
                //alert(tempArray[5]);
                document.getElementById("back").style.display = 'none';
                var distLat;
                var distLng;

                // start the countdown functionality
                // calculating the time in seconds
                var twentyFourHours = hours * 60 * 60;
                //var twentyFourHours = 1 * 60;
                var display = $('#remainingTime');
                Timer(twentyFourHours, display);
                var begin;

                // dislay the timer
                function Timer(duration, display){
                    var timer = duration, hours, minutes, seconds;
                    begin = setInterval(function () {
                        hours = parseInt((timer /3600)%24, 10)
                        minutes = parseInt((timer / 60)%60, 10)
                        seconds = parseInt(timer % 60, 10);

                        hours = hours < 10 ? "0" + hours : hours;
                        minutes = minutes < 10 ? "0" + minutes : minutes;
                        seconds = seconds < 10 ? "0" + seconds : seconds;

                        display.text(hours +":"+minutes + ":" + seconds);

                        if(timer==600){
                            alert(" باقي لك١٠ دقايق " );
                        }
                        if(timer > 0){
                            --timer;
                        }
                        else if(timer==000){
                            alert(" انتهت الرحلة وإن شاء الله تكون استفدت ");
                            window.clearInterval(begin);
                        }

                    }, 1000);

                    var map;

                    var stop = document.getElementById("stop");

                    //create buttons for events
                    var stopbtn = document.createElement("BUTTON");
                    var t = document.createTextNode("أوقف الرحلة");
                    stopbtn.appendChild(t);
                    stopbtn.setAttribute("id","stop");
                    stop.appendChild(stopbtn);

                    //display path
                    distLat = tempArray[1];
                    distLng = tempArray[2];

                    var latLong = new google.maps.LatLng(distLat, distLng);

                    initMap();

                    function initMap() {
                        var directionsService = new google.maps.DirectionsService;
                        var directionsDisplay = new google.maps.DirectionsRenderer;

                        map = new google.maps.Map(document.getElementById('map'), {
                            zoom: 11,
                            center: {lat: 21.389082, lng: 39.857912},
                            //disableDefaultUI: true
                        });

                        directionsDisplay.setMap(map);
                        calculateAndDisplayRoute(directionsService, directionsDisplay);
                    }

                    function calculateAndDisplayRoute(directionsService, directionsDisplay) {
                        directionsService.route({
                            origin: {lat:latitude,lng:longitude},
                            destination: latLong,
                            travelMode: radioValue
                        }, function(response, status) {
                        if (status === 'OK') {
                            directionsDisplay.setDirections(response);
                            //autoUpdate();
                        } else {
                            window.alert('Directions request failed due to ' + status);
                        }
                        });
                    }

                    //tracking part
                    var marker2 = null;
                    var auto;
                    function autoUpdate() {

                        var newLat = position.coords.latitude;
                        var newLng = position.coords.longitude;

                        var newlatLong = new google.maps.LatLng(newLat,newLng);

                        navigator.geolocation.getCurrentPosition(function(position) {  

                        //var newPoint = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                        var latLong2 = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                        if (marker2) {
                          // Marker already created - Move it
                            marker2.setPosition(latLong2);
                        }
                        else {
                          // Marker does not exist - Create it
                            marker2 = new google.maps.Marker({
                            position:newlatLong,
                            map: map
                          });
                        }

                        // Center the map on the new position
                        map.setCenter(latLong2);
                      });

                        auto = setTimeout(autoUpdate, 1000);

                        //Latitude: 21.419833 | Longitude: 39.832421

                        var distance = haversine(21.419833,39.832421,tempArray[1],tempArray[2]);

                        //var distance = haversine(newLat,newLng,tempArray[1],tempArray[2]);

                        function haversine(lat1,lon1,lat2,lon2) {
                          var R = 6371; // Radius of the earth in km
                          var dLat = deg2rad(lat2-lat1);  // deg2rad below
                          var dLon = deg2rad(lon2-lon1); 
                          var a = 
                            Math.sin(dLat/2) * Math.sin(dLat/2) +
                            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
                            Math.sin(dLon/2) * Math.sin(dLon/2)
                            ; 
                          var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
                          var d = R * c; // Distance in km
                          return d;
                        }

                        function deg2rad(deg) {
                          return deg * (Math.PI/180)
                        }

                        if (distance<=1){
                            alert("وصلت/اقتربت من وجهتك");
                            map = new google.maps.Map(document.getElementById('map'), {
                                zoom: 11,
                                center: {lat: 21.389082, lng: 39.857912},
                                //disableDefaultUI: true
                            });
                            var marker = new google.maps.Marker({
                                  position: latLong,
                                  map: map
                            });
                            window.clearInterval(begin);
                            window.clearTimeout(auto);
                            stop.removeChild(stopbtn);
                        }
                    }

                    autoUpdate();

                    //buttons events
                    $("#stop").click(function(){
                        map = new google.maps.Map(document.getElementById('map'), {
                            zoom: 11,
                            center: {lat: 21.389082, lng: 39.857912},
                            //disableDefaultUI: true
                        });
                        var marker = new google.maps.Marker({
                              position: latLong,
                              map: map
                        });
                        window.clearInterval(begin);
                        window.clearTimeout(auto);
                        stop.removeChild(stopbtn);
                    });

                }//end of timer function

            }//end of function showRout()

            }//end of else 
        }); //end of getJSON()

    }, //end of success state

    onError: function(error){
        alert("the code is " + error.code + ". \n" + "message: " + error.message);
    },//end of error state
};//end of app variable 

app.initialize();
}); //end of the whole function 

0 个答案:

没有答案