函数调用不起作用

时间:2015-08-30 15:13:33

标签: javascript

我试图执行一个警告阵列的功能,但它不起作用。当我按下添加按钮时,我应该有一个包含Lat / lng的警报,但是没有警报出现。

您可以在此处查看我的工作代码:jsfiddle。按“添加”按钮以查看此现象。我在第195行中调用了函数f(),但我没有得到任何内容。

我的HTML代码:

<div id="info"></div>
<div id="dvMap"></div>
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="wrapper">Paste coordinate data here:
    <form onSubmit="javascript:return false;">
        <textarea id="Coords" cols="50" rows="25"></textarea>
        <div>
            <input type="button" id="btnAdd" class="Button" value="Add Markers" onClick="ProcessData()">
            <input type="button" id="btnClear" class="Button" value="Clear Map" onClick="Clear()">
        </div>
        <br>
    </form>
</div>

我的Javascript代码:

var directionsDisplay = [];
var directionsService = [];
var map = null;
var g = [];
var path = new Array();
var routeSegment = 0;
var k = 0;

function inizialise() {

    var mapOptions = {

        center: new google.maps.LatLng(33.730166863, 130.7446296584),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
    document.getElementById("Coords").value = '33.29702, 130.54948000000002' + '\n' + '33.29764, 130.54986000000002' + '\n' + '33.29793, 130.55010000000001' + '\n' + '33.298730000000006, 130.55066000000002' + '\n' + '33.299620000000004, 130.55129000000002'

    // calcRoute() ;

}
var MyArray = [];

function Clear() {
    //alert(directionsDisplay.length);

    MyArray = [];

    for (var i = 0; i < directionsDisplay.length; i++) {
        directionsDisplay[i].setMap(null);
    }
    //  directionsDisplay = [];
    document.getElementById("Coords").value = "";
    document.getElementById("Coords").disabled = false;
    document.getElementById("btnAdd").disabled = false;

}

function ProcessData() {
    var Points = document.getElementById("Coords").value

    if (document.getElementById("Coords").value != '') {
        var Points = document.getElementById("Coords").value
        calcRoute(Points);
    }

}
/*
function ProcessData() {
    alert('ok');
    if (document.getElementById("Coords").value != '') {
        var Points = document.getElementById("Coords").value
        AddMarkers(Points); 
    }

}*/


function AddMarkers(data) {

    var MyData = data.substr(0, data.length);
    MyArray = MyData.split("\n");
    //alert(MyArray[2]);
    // calcRoute();
    t();
}


function calcRoute(data) {
    var MyData = data.substr(0, data.length);
    MyArray = MyData.split("\n");
    var input_msg = MyArray;
    var locations = new Array();


    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < input_msg.length; i++) {
        var tmp_lat_lng = input_msg[i].split(",");
        //var s = new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]);
        locations.push(new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]));
        bounds.extend(locations[locations.length - 1]);
    }

    /* var mapOptions = {
        // center: locations[0],
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
    */
    map.fitBounds(bounds);
    var summaryPanel = document.getElementById("directions_panel");
    summaryPanel.innerHTML = "";
    var i = locations.length;
    var index = 0;

    while (i != 0) {

        if (i < 3) {
            var tmp_locations = new Array();
            for (var j = index; j < locations.length; j++) {
                tmp_locations.push(locations[j]);
            }
            drawRouteMap(tmp_locations);
            i = 0;
            index = locations.length;
        }

        if (i >= 3 && i <= 10) {
            console.log("before :fun < 10: i value " + i + " index value" + index);
            var tmp_locations = new Array();
            for (var j = index; j < locations.length; j++) {
                tmp_locations.push(locations[j]);
            }
            drawRouteMap(tmp_locations);
            i = 0;
            index = locations.length;
            console.log("after fun < 10: i value " + i + " index value" + index);
        }

        if (i >= 10) {
            console.log("before :fun > 10: i value " + i + " index value" + index);
            var tmp_locations = new Array();
            for (var j = index; j < index + 10; j++) {
                tmp_locations.push(locations[j]);
            }
            drawRouteMap(tmp_locations);
            i = i - 9;
            index = index + 9;
            console.log("after fun > 10: i value " + i + " index value" + index);
        }
    }
}
var coord = new Array();

function drawRouteMap(locations) {

    var start, end;
    var waypts = [];

    for (var k = 0; k < locations.length; k++) {
        if (k >= 1 && k <= locations.length - 2) {
            waypts.push({
                location: locations[k],
                stopover: true
            });
        }
        if (k == 0) start = locations[k];

        if (k == locations.length - 1) end = locations[k];

    }
    var request = {
        origin: start,
        destination: end,
        waypoints: waypts,
        optimizeWaypoints: false,
        travelMode: google.maps.TravelMode.DRIVING
    };
    console.log(request);

    directionsService.push(new google.maps.DirectionsService());
    var instance = directionsService.length - 1;
    directionsDisplay.push(new google.maps.DirectionsRenderer({
        preserveViewport: true
    }));
    directionsDisplay[instance].setMap(map);
    directionsService[instance].route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            console.log(status);
            directionsDisplay[instance].setDirections(response);
            var f = response.routes[0];
           // var summaryPanel = document.getElementById("directions_panel");
            var route = directionsDisplay[instance].getDirections().routes[0];
            // var routes = response.routes;
            var points = route.overview_path;
            //alert(points);
            var ul = document.getElementById("directions_panel");


               var legs = response.routes[0].legs;
            for (i = 0; i < legs.length; i++) {
                var steps = legs[i].steps;
                for (j = 0; j < steps.length; j++) {
                    var nextSegment = steps[j].path;
                    for (k = 0; k < nextSegment.length; k++) {
                       // alert(nextSegment[k]);
                        var li = document.createElement('P');
                li.innerHTML = getLatLng(nextSegment[k]);
                ul.appendChild(li);
                       // polyline.getPath().push(nextSegment[k]);
                        //bounds.extend(nextSegment[k]);
                   coord.push( getLatLng(nextSegment[k]));
                      f(coord);   

                    }
                }

            }




        } else {
            alert("directions response " + status);
        }


    });
}

 function f( r) {

    alert(r);
} 

function getLatLng(point) {

//alert(MyArray.length);

    var lat = point.lat(),
        lng = point.lng();
    var tmp = MyArray[k].split(",");
    //  alert(  Math.abs(parseFloat(tmp[0]- lat)) )
    if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
        k++;
        // alert(k);
//if(k==MyArray.length) { f('animation');  }
        return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
    } else {
        return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
    }
}


google.maps.event.addDomListener(window, 'load', inizialise);

问题代码在第195行:我致电f(coord),但警报未显示。我已经定义了f函数:

 function f(r) {
    alert(r);
} 

2 个答案:

答案 0 :(得分:1)

您使用第173行中的对象覆盖f

var f = response.routes[0];

因此,当您尝试呼叫f时,它不是一个函数,而是一个对象(在调用之前尝试记录typeof f:您将获得'对象')。

答案 1 :(得分:0)

我设法解决了这个问题。我编辑了我的功能&#39; getLatLng()&#39;如:

&#13;
&#13;
function getLatLng(point, array) {
    //alert(k);
    var lat = point.lat(),
        lng = point.lng();
    var tmp = MyArray[k].split(",");
    //  alert(  Math.abs(parseFloat(tmp[0]- lat)) )
    if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
        k++;
        array.push({
        "lat": lat ,
         "lng": lng,
         "stop":1
        });
        return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
    } else {
        
        array.push({
        "lat": lat ,
         "lng": lng,
         "stop":1
        });
        return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
    }

}
&#13;
&#13;
&#13;

现在我可以访问我的数组元素了。这是我的code