数组的旧值替换为数组的新值

时间:2013-10-15 11:33:10

标签: javascript arrays google-maps

我想做的是谷歌地图的onclick。试图创建包含地址的数组。问题是当我提醒数组时它只显示当前值 我也尝试了waypts.length,它只提醒1.这意味着当我点击谷歌地图时,数组值会被替换。 那似乎是什么问题?

代码:

  function initialize() {
  var geocoder = new google.maps.Geocoder();
  var waypts=[];
  var mapOptions = {
   zoom: 11,
   center: new google.maps.LatLng(23.0171240, 72.5330533),
   mapTypeId: google.maps.MapTypeId.ROADMAP
   };
   var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
  google.maps.event.addListener(map, 'click', function(e) {
  placeMarker(e.latLng, map);
  var input=e.latLng;
  var lat = parseFloat(input.lat());
  var lng = parseFloat(input.lng());
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
       var add=results[0].formatted_address;
       waypts.push({
        location:add,
        stopover:true
       });
       var lngth=waypts.length;
       alert(JSON.stringify(waypts));
    }
  });
          <!--  **************    for route between markers   *******************  -->
  var directionsDisplay;
  var directionsService = new google.maps.DirectionsService();
  //directionsDisplay = new google.maps.DirectionsRenderer();
  directionsDisplay = new google.maps.DirectionsRenderer({
  suppressMarkers: true, //false it if you want a marker from the direction service 
  polylineOptions: {
      strokeColor: 'green', //"black",
      strokeOpacity: 1.0,
      strokeWeight: 3
    }
  });

    var lngth=waypts.length;
    var start = waypts[0][0];//"Bopal, Ahmedabad, Gujarat, India";
    var end = waypts[waypts.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";

    //remove start destination from array
    var a=waypts.shift();
    //remove end destination from array
    waypts.pop();

    var request = {
          origin:start,
          destination:end,
          waypoints:waypts,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
    });
    directionsDisplay.setMap(map);

 });


}
   function placeMarker(position, map) {
  var marker = new google.maps.Marker({
    position: position,
    map: map
  });
  map.panTo(position);
}

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

提前致谢。

1 个答案:

答案 0 :(得分:1)

我假设它存在于函数内部。

代码的问题可能是waypts成为局部变量。

如果在其他地方引用,则无法获取该值。

每次调用函数时都会重新初始化变量,因此存储在数组中的所有先前值都将丢失。

使waypts全局并尝试在函数外部定义变量。