在javascript

时间:2015-07-08 03:31:53

标签: javascript google-maps

我有一个demo1 Here,还有另一个demo2 here。我想在html表单和Google地图之间准确包含demo 2输出。我是js的新手。当我通过将演示2的特定功能粘贴到演示1中来尝试它时,它不起作用。我怎么做?

var map;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

function initialize() {
    //INITIALIZE GLOBAL VARIABLES
    var zipCodesToLookup1 = new Array(document.getElementById("PortZip").value, document.getElementById("ImporterZip").value, document.getElementById("ExporterZip").value, document.getElementById("PortZip").value);
    var output = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
    var output = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
    var difference = "0";
    var totalDist = 0;
    // document.write(difference);
    //EXECUTE THE DISTANCE MATRIX QUERY
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
        origins: zipCodesToLookup1,
        destinations: zipCodesToLookup1,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL
    }, function (response, status) {
        if (status == google.maps.DistanceMatrixStatus.OK) {
            var origins = response.originAddresses;
            var destinations = response.destinationAddresses;
            for (var i = 0; i < origins.length - 1; i++) {
                var results = response.rows[i].elements;
                output += '<tr><td>' + origins[i] + '</td><td>' + destinations[i + 1] + '</td><td>' + results[i + 1].distance.text + '</td></tr>';
                if (i != 0) {
                    totalDist += results[i + 1].distance.value;
                } else {
                    totalDist -= results[i + 1].distance.value;
                }

            }
            output += '<tr><td></td><td>OUT OF ROUTE DISTANCE -</td><td>' + (totalDist / 1000 * 0.621371).toFixed(0) + ' mi</td></tr>';
            document.getElementById('zip_code_output').innerHTML = '<table cellpadding="5">' + output + '</table>';
        }
    });
}

//FUNCTION TO LOAD THE GOOGLE MAPS API
function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyCDZpAoR25KSkPTRIvI3MZoAg1NL6f0JV0&sensor=false&callback=initialize";
    document.body.appendChild(script);
}
<form>
    Calculation of OUT OF ROUTE DISTANCE.<br>
    Enter 5 digit VALID US ZipCodes<br>
    Port ZipCode:<br>
    <input type="text" id="PortZip" value="31402"><br>
    Importer ZipCode:<br>
    <input type="text" id="ImporterZip" value="30308"><br>
    Exporter ZipCode:<br>
    <input type="text" id="ExporterZip" value="30901"><br>
    <input type="button" value="Calculate" onclick="loadScript()" />
</form>

<div id="zip_code_output"></div>
<div id="map_canvas" style="width:650px; height:600px;"></div>

2 个答案:

答案 0 :(得分:1)

您有2种不同的结果,来自2种不同的异步方法(函数)。

您需要获取两次结果并同时显示,我建议您使用async库。这有一个名为 parallel 的方法,当两个进程必须结束时执行回调:

例如:

function calculeRouteAndShow () {
    var service = new google.maps.DistanceMatrixService();
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();

    var zipCodeOutput = document.getElementById('zip_code_output');
    var importZip = document.getElementById('ImporterZip').value;
    var exportZip = document.getElementById('ExporterZip').value;
    var portZip = document.getElementById("PortZip").value;

    async.parallel({
        getDistance: funcion (done) {
            service.getDistanceMatrix({
                origins:      [PortZip, ImportZip, exportZip],
                destinations: [PortZip, ImportZip, exportZip],
                travelMode:   google.maps.TravelMode.DRIVING,
                unitSystem:   google.maps.UnitSystem.IMPERIAL
            }, function(response, status) {

                if (status !== google.maps.DistanceMatrixStatus.OK) {
                    return done(null, response);
                }

                var origins = response.originAddresses;
                var destinations = response.destinationAddresses;
                var output = "";

                for(var i=0; i < origins.length-1; i++) {
                    var results = response.rows[i].elements;
                    output += '<tr><td>' + origins[i] + '</td><td>' + destinations[i+1] + '</td><td>' + results[i+1].distance.text + '</td></tr>';
                    if (i != 0){
                        totalDist += results[i+1].distance.value;
                    }
                    else {
                        totalDist -= results[i+1].distance.value;
                    }

                }

                output += '<tr><td></td><td>OUT OF ROUTE DISTANCE -</td><td>'+(totalDist/1000*0.621371).toFixed(0)+ ' mi</td></tr>';

                return done(null, output);

            });

        },

        calculateRoute: function (done) {

            var waypts = [{
                location: ImportZip
            },{
                location: exportZip 
            }];;

            var request = {
                origin: portZip,
                destination: portZip,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: google.maps.TravelMode.DRIVING
            };

            directionsService.route(request, function(response, status) {
                if (status !== google.maps.DirectionsStatus.OK) {
                    return done(status);
                }

                return done(null, response);

            });
        }

    }, function (err, responses) {

        if (err) {
            alert("We have an error here :(");
            return;
        }

        zipCodeOutput.innerHTML = '<table cellpadding="5">' + responses.getDistance + '</table>';
        directionsDisplay.setDirections(responses.calculateRoute);

    });

} 

我希望这对你有帮助,对不起我的英语很差。

答案 1 :(得分:0)

@Exos我的代码如下:

<body onload="initialize()">
<script type="text/javascript">
function initialize() {
     //CONVERT THE MAP DIV TO A FULLY-FUNCTIONAL GOOGLE MAP
     var mapOptions = {
          zoom:      8,
          center:    new google.maps.LatLng(-34.397, 150.644),
          mapTypeId: google.maps.MapTypeId.ROADMAP
     }
     var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);


      var rendererOptions = { map: map };
      directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

    var point1 = document.getElementById('PortZip').value;
    var point2 = document.getElementById('ImporterZip').value;
    var point3 = document.getElementById('ExporterZip').value;
    var point4 = document.getElementById('ExporterZip').value;

    var wps = [{ location: point2 }, { location: point3 }];

    var org = document.getElementById('PortZip').value;
    var dest = document.getElementById('PortZip').value;

    var request = {
            origin: org,
            destination: dest,
            waypoints: wps,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

    directionsService = new google.maps.DirectionsService();
    directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
                else
                    alert ('failed to get directions');
});

     //INITIALIZE GLOBAL VARIABLES
    var zipCodesToLookup1 = new Array(document.getElementById("PortZip").value, document.getElementById("ImporterZip").value, document.getElementById("ExporterZip").value, document.getElementById("PortZip").value);
            var output           = '<tr><th scope="col">Leg</th><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';

     var difference = "0";
     var totalDist = 0;
    // document.write(difference);
     //EXECUTE THE DISTANCE MATRIX QUERY
     var service = new google.maps.DistanceMatrixService();
     service.getDistanceMatrix({
          origins:      zipCodesToLookup1,
          destinations: zipCodesToLookup1,
          travelMode:   google.maps.TravelMode.DRIVING,
          unitSystem:   google.maps.UnitSystem.IMPERIAL
     }, function(response, status) {
          if(status == google.maps.DistanceMatrixStatus.OK) {
               var origins = response.originAddresses;
               var destinations = response.destinationAddresses;
               var customText = ["<i>From Port to Exporter</i>",
                  "<i>From Exporter to Importer</i>",
                  "<i>From Importer back to Port</i>"];
               for(var i=0; i < origins.length-1; i++) {
                     var results = response.rows[i].elements;
                     output += '<tr><td>' + customText[i] + '</td><td>' + origins[i] + '</td><td>' + destinations[i+1] + '</td><td>' + results[i+1].distance.text + '</td></tr>';
                     if (i != 0){
                     totalDist += results[i+1].distance.value;
                     }
                     else {
                     totalDist -= results[i+1].distance.value;
                     }

               }
              output += '<tr><td></td><td></td><td><b>OUT OF ROUTE DISTANCE</b></td><td><b>'+(totalDist/1000*0.621371).toFixed(0)+ ' mi</b></td></tr>';              
              document.getElementById('zip_code_output').innerHTML = '<table border = "2px" cellpadding="5">' + output + '</table><br>';
         }
     });

function scrollWin() {
    window.scrollBy(0, 580);
}
scrollWin();

}

//FUNCTION TO LOAD THE GOOGLE MAPS API
function loadScript() {

     var script  = document.createElement("script");
     script.type = "text/javascript";
     script.src  = "http://maps.googleapis.com/maps/api/js?key=KEY&sensor=false&callback=initialize";
     document.body.appendChild(script);

}

</script>
</body>