如果更改位置(目的地),则Google Maps v3无法读取未定义的属性“ setOptions”

时间:2018-06-24 12:55:17

标签: javascript google-maps google-maps-api-3

我正在使用Google Maps Javascript API v3创建项目以获取建议的路线(路线),并且如果将第一个目的地更改为一些建议路线,而将第二个目的地更改为具有很多建议路线的路线,则会收到错误消息。但是,如果我从多条路线改为更少的路线(pekanbaru到dumai有3条路线,pekanbaru到duri有2条路线),则不会出现错误。

图像错误。 Google Maps Error

我的JavaScript代码:

    <script>
    function initMap() {
    var polyOptions = [];
    var markerArray = [];

    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var stepDisplay = new google.maps.InfoWindow;

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 7,
      center: {lat: 0.50404, lng: 102.4579712}
    });


    var onChangeHandler = function() {
        removeLine(polyOptions,directionsDisplay);
                polyOptions = [];
        calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map,polyOptions);
    };
    document.getElementById('start').addEventListener('change', onChangeHandler);
    document.getElementById('finish').addEventListener('change', onChangeHandler);
  }

  function calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map,polyOptions) {
    for (var i = 0; i < markerArray.length; i++) {
      markerArray[i].setMap(null);
    }
    directionsService.route({
      origin: document.getElementById('start').value,
      destination: document.getElementById('finish').value,
      travelMode: 'DRIVING',
      optimizeWaypoints: false,
      provideRouteAlternatives: true,
    }, function(response, status) {
      if (status === 'OK') {
            var pathPoints ;
            var routeLeg;
            for (var i = 0, len = response.routes.length; i < len; i++) {
                routeLeg = response.routes[i].legs[0];
                    pathPoints = response.routes[i].overview_path;
                    var polyPath = new google.maps.Polyline({
                      path: pathPoints,
                      strokeColor: "#16a085",
                      strokeOpacity: 1.0,
                      strokeWeight: 5,
                      map: map,
                      clickable:true,

                    });
                    polyOptions.push(polyPath);

                    if (i == 0) polyOptions[0].setOptions({
                  strokeColor: '#c0392b',
                  strokeOpacity: 1.0,
                                zIndex: 1
                });

                polyOptions[polyOptions.length - 1].setPath(pathPoints);

            directionsDisplay.setRouteIndex(i);
            directionsDisplay.setDirections(response);
            directionsDisplay.setOptions({ 
              polylineOptions: polyOptions,
              suppressPolylines : true,
            });
            directionsDisplay.setPanel(document.getElementById('panel'));
            directionsDisplay.setMap(map);

            clickLine(polyOptions,directionsDisplay,i);
        }

        clickPanel(polyOptions,directionsDisplay); 

        $("#error").empty();
        $("#error").removeClass();
      } else {
        directionsDisplay.setMap(null);
            directionsDisplay.setPanel(null);
       $("#error").addClass("badge badge-danger");
        $("#error").text("Tidak dapat menemukan nama lokasi, status error: "+status);
      }
    });
  }

  function showSteps(directionResult, markerArray, stepDisplay, map) {
    var myRoute = directionResult.routes[0].legs[0];
    for (var i = 0; i < myRoute.steps.length; i++) {
      var marker = markerArray[i] = markerArray[i] || new google.maps.Marker;
      marker.setMap(map);
      marker.setPosition(myRoute.steps[i].start_location);
      attachInstructionText(
          stepDisplay, marker, myRoute.steps[i].instructions, map);
    }
  }

  function attachInstructionText(stepDisplay, marker, text, map) {
    google.maps.event.addListener(marker, 'click', function() {
      stepDisplay.setContent(text);
      stepDisplay.open(map, marker);
    });
  }

  function removeLine(options,directionsDisplay) {
          for(var i = 0; i < options.length; i++){
            options[i].setMap(null);
            options[i].setVisible(false);
      directionsDisplay.setMap(null);
          }
        }

        function clickPanel(polyline,directionsDisplay,index){
        console.log(directionsDisplay.getRouteIndex());
    google.maps.event.addListener(directionsDisplay,'routeindex_changed',function(){
                    for (var i = 0; i < polyline.length; i++) {
          polyline[i].setOptions({
            strokeOpacity: 1.0,
            strokeColor: "#16a085",
            zIndex: 0
          });
                    }

                    polyline[this.getRouteIndex()].setOptions({
          strokeOpacity: 1.0,
          strokeColor: "#c0392b",
          zIndex: 1
        });

    });        

        }

        function clickLine(polyline,directionsDisplay,index){
            google.maps.event.addListener(polyline[polyline.length - 1], 'click', function(evt) {
                 for (var i = 0; i < polyline.length; i++) {
          polyline[i].setOptions({
            strokeOpacity: 1.0,
            strokeColor: "#16a085",
            zIndex: 0
          });
        }
        this.setOptions({
          strokeOpacity: 1.0,
          strokeColor: "#c0392b",
          zIndex: 1
        });
                directionsDisplay.setRouteIndex(index);  
        });
        }

</script>

行中的错误代码
directionsDisplay.setRouteIndex(i);

在函数clickPanel()

polyline[this.getRouteIndex()].setOptions({
          strokeOpacity: 1.0,
          strokeColor: "#c0392b",
          zIndex: 1
        });

1 个答案:

答案 0 :(得分:0)

问题出在:

function clickPanel(polyline, directionsDisplay, index) {
  google.maps.event.addListener(directionsDisplay, 'routeindex_changed', function() {
    for (var i = 0; i < polyline.length; i++) {
      polyline[i].setOptions({
        strokeOpacity: 1.0,
        strokeColor: "#16a085",
        zIndex: 0
      });
    }
    polyline[this.getRouteIndex()].setOptions({//<= this line (as you indicated in your question)
      strokeOpacity: 1.0,
      strokeColor: "#c0392b",
      zIndex: 1
    });
  });
}

在这种情况下,路由索引大于折线数组的大小,如果我防止这种情况,错误就会消失:

function clickPanel(polyline, directionsDisplay, index) {
  google.maps.event.addListener(directionsDisplay, 'routeindex_changed', function() {
    for (var i = 0; i < polyline.length; i++) {
      polyline[i].setOptions({
        strokeOpacity: 1.0,
        strokeColor: "#16a085",
        zIndex: 0
      });
    }
    // protect against out of range error
    if (this.getRouteIndex() < polyline.length) {
      polyline[this.getRouteIndex()].setOptions({
        strokeOpacity: 1.0,
        strokeColor: "#c0392b",
        zIndex: 1
      });
    }
  });
}

您可能希望将其设置为折线数组的最后一个条目,但是在这种情况下只需忽略它就可以了。

proof of concept fiddle

代码段:

function initMap() {
  var polyOptions = [];
  var markerArray = [];
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer();
  var stepDisplay = new google.maps.InfoWindow();

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {
      lat: 0.50404,
      lng: 102.4579712
    }
  });

  var onChangeHandler = function() {
    removeLine(polyOptions, directionsDisplay);
    polyOptions = [];
    calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map, polyOptions);
  };
  document.getElementById('start').addEventListener('change', onChangeHandler);
  document.getElementById('finish').addEventListener('change', onChangeHandler);
}

function calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map, polyOptions) {
  for (var i = 0; i < markerArray.length; i++) {
    markerArray[i].setMap(null);
  }
  directionsService.route({
    origin: document.getElementById('start').value,
    destination: document.getElementById('finish').value,
    travelMode: 'DRIVING',
    optimizeWaypoints: false,
    provideRouteAlternatives: true,
  }, function(response, status) {
    if (status === 'OK') {
      var pathPoints;
      var routeLeg;
      for (var i = 0, len = response.routes.length; i < len; i++) {
        routeLeg = response.routes[i].legs[0];
        pathPoints = response.routes[i].overview_path;
        var polyPath = new google.maps.Polyline({
          path: pathPoints,
          strokeColor: "#16a085",
          strokeOpacity: 1.0,
          strokeWeight: 5,
          map: map,
          clickable: true,

        });
        polyOptions.push(polyPath);

        if (i == 0) polyOptions[0].setOptions({
          strokeColor: '#c0392b',
          strokeOpacity: 1.0,
          zIndex: 1
        });

        polyOptions[polyOptions.length - 1].setPath(pathPoints);

        directionsDisplay.setRouteIndex(i);
        directionsDisplay.setDirections(response);
        directionsDisplay.setOptions({
          polylineOptions: polyOptions,
          suppressPolylines: true,
        });
        directionsDisplay.setPanel(document.getElementById('panel'));
        directionsDisplay.setMap(map);

        clickLine(polyOptions, directionsDisplay, i);
      }

      clickPanel(polyOptions, directionsDisplay);

      $("#error").empty();
      $("#error").removeClass();
    } else {
      directionsDisplay.setMap(null);
      directionsDisplay.setPanel(null);
      $("#error").addClass("badge badge-danger");
      $("#error").text("Tidak dapat menemukan nama lokasi, status error: " + status);
    }
  });
}

function showSteps(directionResult, markerArray, stepDisplay, map) {
  var myRoute = directionResult.routes[0].legs[0];
  for (var i = 0; i < myRoute.steps.length; i++) {
    var marker = markerArray[i] = markerArray[i] || new google.maps.Marker;
    marker.setMap(map);
    marker.setPosition(myRoute.steps[i].start_location);
    attachInstructionText(
      stepDisplay, marker, myRoute.steps[i].instructions, map);
  }
}

function attachInstructionText(stepDisplay, marker, text, map) {
  google.maps.event.addListener(marker, 'click', function() {
    stepDisplay.setContent(text);
    stepDisplay.open(map, marker);
  });
}

function removeLine(options, directionsDisplay) {
  for (var i = 0; i < options.length; i++) {
    options[i].setMap(null);
    options[i].setVisible(false);
    directionsDisplay.setMap(null);
  }
}

function clickPanel(polyline, directionsDisplay, index) {
  google.maps.event.addListener(directionsDisplay, 'routeindex_changed', function() {
    for (var i = 0; i < polyline.length; i++) {
      polyline[i].setOptions({
        strokeOpacity: 1.0,
        strokeColor: "#16a085",
        zIndex: 0
      });
    }
    if (this.getRouteIndex() < polyline.length) {
      polyline[this.getRouteIndex()].setOptions({
        strokeOpacity: 1.0,
        strokeColor: "#c0392b",
        zIndex: 1
      });
    }
  });
}

function clickLine(polyline, directionsDisplay, index) {
  google.maps.event.addListener(polyline[polyline.length - 1], 'click', function(evt) {
    for (var i = 0; i < polyline.length; i++) {
      polyline[i].setOptions({
        strokeOpacity: 1.0,
        strokeColor: "#16a085",
        zIndex: 0
      });
    }
    this.setOptions({
      strokeOpacity: 1.0,
      strokeColor: "#c0392b",
      zIndex: 1
    });
    directionsDisplay.setRouteIndex(index);
  });
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

#map {
  height: 90%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="start" value="Dumai" />
<input id="finish" value="Pekanbaru" />
<div id="error"></div>
<div id="map"></div>
<div id="panel"></div>