javascript数组中的值不是第一次设置

时间:2012-06-03 08:27:00

标签: javascript google-maps

consolidated_cord [] 下面的代码值中,第一次没有设置值。

点击按钮时会调用脚本。

<html>
<head>
  <title>Map Test</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
      type="text/javascript"></script>

    <script type="text/javascript" src="js/map-script.js"></script>

 <style type="text/css">
      body {
        font-family: sans-serif;
        font-size: 14px;
      }
      #map_canvas {
        height: 400px;
        width: 600px;
        margin-top: 0.6em;
      }
    </style>
    <SCRIPT>

// jQ Block
$(document).ready(function(){
    var map, infowindow, autocomplete, place, marker;
    var position;
    var startpt, endpt;
    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    var geocoder;
    var consolidated_cord = [];

    {   // initializtion block -- will load default map

        directionsDisplay = new google.maps.DirectionsRenderer({draggable: true});
        position = new google.maps.LatLng(48.8742, 2.3470); 
        var mapOptions = {
            center: position,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);

        // Start Point
        startpt = document.getElementById('start');
        autocomplete = new google.maps.places.Autocomplete(startpt);
        autocomplete.bindTo('bounds', map);

        endpt = document.getElementById('end');
        autocomplete = new google.maps.places.Autocomplete(endpt);
        autocomplete.bindTo('bounds', map);


        marker = new google.maps.Marker(
            {
                position: position,
                draggable:true,
                animation: google.maps.Animation.DROP,
                map: map
            }
        );
        google.maps.event.addListener(marker, 'click', toggleBounce);
        directionsDisplay.setMap(map);  
    }


    /*
    *   "+"click - add input textfield
    */
    var i = 1;
    $('#addTextBox').click(function(){
        if(i<=3){
            var id = "wp"+(i);
            $('<input id="'+id+'" type="text" size=50><br/>').fadeIn('slow').appendTo('#wayPointContainer');
            autocomplete = new google.maps.places.Autocomplete(document.getElementById(id));
            autocomplete.bindTo('bounds', map);
            i++;
        }else{
            alert('Sorry Upto 5 waypoints are allowed');
        }
    });

    $('#Go').click(function(){


        if ( $('#start').val() == "" || $('#end').val() == "" ){
            alert('Start or End Empty');
            return false;
        }

        // Array for storing all entered locations - will be used for geocoding
        var loc_arr_geocode = [];
        loc_arr_geocode.push($('#start').val());


        // Checking if any waypoint available
        var numWp = $('#wayPointContainer input').size();
        //pushing waypoints in an array
        var waypts = [];
        for(var counter = 1; counter <= numWp; counter++){
            if ($('#wp'+counter).val() != ""){
                waypts.push({
                    location: $('#wp'+counter).val(),
                    stopover:true
                });
                loc_arr_geocode.push($('#wp'+counter).val());
            }
        }

        loc_arr_geocode.push($('#end').val());

        var request = {
            origin:startpt.value,
            destination:endpt.value,
            waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });


        //fetching coordinated
        fetchCoordinates(loc_arr_geocode);

        //saving cordintes in hidden form field

    });

    //Geocoder to fetch coordinates
    function fetchCoordinates(loc_arr_geocode){


        geocoder = new google.maps.Geocoder();
        for( var i=0; i < loc_arr_geocode.length; i++){
            geocoder.geocode( { 'address': loc_arr_geocode[i]}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    consolidated_cord.push(results[0].geometry.location);
                }else{
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }

        save_cord();
    }

    function save_cord(){
        alert(consolidated_cord[0]);
        //$('#submit_cord').submit();
    }

    function toggleBounce() {
        if (marker.getAnimation() != null) {
          marker.setAnimation(null);
        } else {
          marker.setAnimation(google.maps.Animation.BOUNCE);
        }
    }


});

    </SCRIPT>


</head>

<body>

    <input id="start" type="text" size="50"> <br/>
        <div id="wayPointContainer"></div>
    <input id="end" type="text" size="50"> <br/>

    <input id="addTextBox" type="button" value="+">
    <input type="button" id="Go" value="Go"/>
    <div id="map_canvas"></div>

    <form id="submit_cord" name="submit_cord" action="save_cord.php" method="post">
        <input type="hidden" id="cord" name="cord"/>
    </form>

</body>
</html>

当我点击按钮时,它会发出'undefined'警告。 但第二次它会提醒坐标。

1 个答案:

答案 0 :(得分:2)

地理编码会强制执行异步请求。获得结果需要一些时间,但您可以立即致电save_cord()。第二次点击时得到的结果是第一次请求的结果。

改为在geocoder.geocode()的回调中调用该函数。