2014-11-18 2 views
-1

Я пытаюсь построить маршруты с использованием DirectionService API, предоставив путевые точки (больше 8). Поскольку DirectionService API позволяет максимально использовать 8 путевых точек (для общего использования), я рекурсивно выполняю вызов для обработки путевой точки, по 8 пунктов за раз.Uncaught TypeError: Не удается прочитать свойство 'lat' of null Исключение

Всякий раз, когда он пытается построить маршрут в методе «setDirections», его метательная ошибка, говорящая «Uncaught TypeError: Can not read property» lat «null».

JavaScript код (geojson_2.js):

function RouteService(oGoogleMaps, oMap) { 
    var requestArray = [], renderArray = [], data, limit, index = 0, MAX_WAY_POINT_ALLOWED = 20; 
    var directionService = new oGoogleMaps.DirectionsService({ 
     map: oMap 
    }); 
    var nextRequest = function() { 
     index++; 
     if (index >= requestArray.length) { 
      return; 
     } 
     makeRequests(requestArray[index]); 
    }; 

    this.getVariables = function (sVariable) { 
     return eval(sVariable); 
    }; 

    var directionResults = function (result, status) { 
     if (status == oGoogleMaps.DirectionsStatus.OK) { 

      // Create a unique DirectionsRenderer 'i' 
      renderArray[index] = new oGoogleMaps.DirectionsRenderer(); 

      // Some unique options from the colorArray so we can see the routes 
      renderArray[index].setOptions({ 
       preserveViewport: true, 
       suppressInfoWindows: true, 
       polylineOptions: { 
        strokeWeight: 4, 
        strokeOpacity: 0.8 
       }, 
       markerOptions: { 
        icon: { 
         path: oGoogleMaps.SymbolPath.BACKWARD_CLOSED_ARROW, 
         scale: 3 
        } 
       }, 
       map : oMap 
      }); 

      // Use this new renderer with the result 
      renderArray[index].setDirections(result); 

     } 
     nextRequest(); 
    }; 

    var makeRequests = function (oRequest) { 
     directionService.route(oRequest.request, directionResults); 
    }; 

    this.generateRequests = function (oResponseData) { 
     requestArray = []; 
     var lastpoint = null, waypts = []; 
     for (var waypoint = 0, limit = oResponseData.length; waypoint < limit; waypoint++) { 
      if (lastpoint && (lastpoint.lng() === oResponseData[waypoint].lng() && lastpoint.lat() === oResponseData[waypoint].lat())) { 
       // Duplicate of of the last waypoint - don't process 
       continue; 
      } 
      lastpoint = oResponseData[waypoint] 

      waypts.push({ 
       location: oResponseData[waypoint], 
       stopover: true 
      }); 
     } 
     var start, finish, routeIndex = 0, maxRequest = Math.ceil(oResponseData.length/MAX_WAY_POINT_ALLOWED); 

     for (var pointCount = 0; routeIndex < maxRequest; routeIndex++, pointCount = pointCount + MAX_WAY_POINT_ALLOWED) { 
      var tempWayPts = waypts.slice(pointCount, pointCount + MAX_WAY_POINT_ALLOWED); 
      // Grab the first waypoint for the 'start' location 
      start = (tempWayPts.shift()).location; 
      // Grab the last waypoint for use as a 'finish' location 
      finish = tempWayPts.pop(); 
      if (finish === undefined) { 
       // Unless there was no finish location for some reason? 
       finish = start; 
      } else { 
       finish = finish.location; 
      } 

      var request = { 
       origin: start, 
       destination: finish, 
       waypoints: tempWayPts, 
       travelMode: oGoogleMaps.TravelMode.DRIVING 
      }; 

      requestArray.push({"routeIndex": routeIndex, "request": request}); 
     } 

     makeRequests(requestArray[index]); 
    } 
}; 

function MapService() { 

    var routeService = null; 
    var oGoogleMaps = google.maps, oMap, oMapOptions = { 
     minZoom: 2, 
     zoom: 3, 
     panControl: true, 
     panControlOptions: { 
      position: oGoogleMaps.ControlPosition.TOP_LEFT 
     }, 
     zoomControl: true, 
     zoomControlOptions: { 
      style: oGoogleMaps.ZoomControlStyle.SMALL, 
      position: oGoogleMaps.ControlPosition.TOP_LEFT 
     }, 
     scaleControl: true, 
     mapTypeControl: true, 
     streetViewControl: true, 
     overviewMapControl: true, 
     mapTypeId: oGoogleMaps.MapTypeId.ROADMAP, 
     styles: [ 
      { 
       featureType: "water", 
       elementType: "geometry", 
       stylers: [{ 
        color: '#4eb4e5' 
       }, { 
        saturation: -10 
       }, { 
        lightness: 40 
       }] 
      }, { 
       featureType: "road", 
       stylers: [{ 
        hue: '#ffc000' 
       }, { 
        saturation: -30 
       }, { 
        lightness: 10 
       }] 
      }, { 
       featureType: "poi", 
       stylers: [{ 
        hue: '#8CC63F' 
       }, { 
        saturation: -10 
       }, { 
        lightness: 10 
       }] 
      }] 
    }; 

    this.getVariables = function (sVariable) { 
     var result; 
     if ((result = eval(sVariable)) != undefined) { 
      result = routeService.getVariables(sVariable); 
     } 
     return result; 
    }; 

    this.loadMap = function (targetDiv) { 
     oMap = new oGoogleMaps.Map(document.getElementById(targetDiv), oMapOptions); 
     routeService = new RouteService(oGoogleMaps, oMap); 
     //plotRoutes(oMap); 
     //some = oMap.data.addGeoJson(oPolyLinePath); 
     // To delete the path 
     // oMap.data.remove(some[0]); 
    }; 

    this.plotRoutes = function() { 
     var oRouteMap = [ 
      new oGoogleMaps.LatLng("29.968313", "-95.4155288"), 
      new oGoogleMaps.LatLng("29.9673186", "-95.40616060000002"), 
      new oGoogleMaps.LatLng("29.9658338", "-95.4150376"), 
      new oGoogleMaps.LatLng("29.9682822", "-95.4153981"), 
      new oGoogleMaps.LatLng("29.9679707", "-95.41517220000003"), 
      new oGoogleMaps.LatLng("29.9679707", "-95.41517220000003"), 
      new oGoogleMaps.LatLng("29.9682842", "-95.41553049999999"), 
      new oGoogleMaps.LatLng("29.9682842", "-95.41553049999999"), 
      new oGoogleMaps.LatLng("29.9682877", "-95.41551320000002"), 
      new oGoogleMaps.LatLng("29.9682707", "-95.41550280000001"), 
      new oGoogleMaps.LatLng("29.9682878", "-95.4155169"), 
      new oGoogleMaps.LatLng("29.9682721", "-95.41551179999999"), 
      new oGoogleMaps.LatLng("29.9682784", "-95.41550799999999"), 
      new oGoogleMaps.LatLng("29.9682884", "-95.41551449999997"), 
      new oGoogleMaps.LatLng("29.968295", "-95.41549050000003"), 
      new oGoogleMaps.LatLng("29.9682868", "-95.41547450000002"), 
      new oGoogleMaps.LatLng("29.9682774", "-95.41546470000003"), 
      new oGoogleMaps.LatLng("29.9682871", "-95.4154163"), 
      new oGoogleMaps.LatLng("29.9683139", "-95.41551659999999"), 
      new oGoogleMaps.LatLng("29.9683222", "-95.4155614"), 
      new oGoogleMaps.LatLng("29.9683159", "-95.41555370000003"), 
      new oGoogleMaps.LatLng("29.9683428", "-95.41555949999997"), 
      new oGoogleMaps.LatLng("29.9683213", "-95.41557449999999"), 
      new oGoogleMaps.LatLng("29.9683153", "--95.4155255"), 
      new oGoogleMaps.LatLng("29.9683094", "-95.4155313"), 
      new oGoogleMaps.LatLng("29.9683223", "-95.41553329999999"), 
      new oGoogleMaps.LatLng("29.9682942", "-95.41538589999999"), 
      new oGoogleMaps.LatLng("29.965987", "-95.40982959999997") 
     ]; 
     routeService.generateRequests(oRouteMap); 
    } 
}; 


$(document).ready(function() { 
    var mapService = new MapService(); 
    mapService.loadMap("mapDiv"); 
    mapService.plotRoutes(); 
}); 

HTML код:

<div id="mapDiv"></div> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script src="https://maps.googleapis.com/maps/api/js?libraries=weather,places&sensor=false"></script> 
<script type="text/javascript" src="geojson_2.js"></script> 

Может кто-нибудь, пожалуйста, помогите мне это.

Благодаря

+0

Как-то одна из ваших точек «null» вместо объекта LatLng, поэтому метод не может прочитать свою широту. – rupps

+0

Согласен, что хотя бы один из элементов в 'oResponseData' не будет объектом LatLng. –

ответ

0

Что-то попробовать - сочинить waypts с oResponseData.reduce() следующим образом:

var waypts = oResponseData.reduce(function(a, waypoint) { 
    var lastpoint = a[a.length - 1]; 
    if(!lastpoint || !waypoint.equals(lastpoint.location)) { 
     a.push({ location:waypoint, stopover:true }); 
    } 
    return a; 
}, []); 

Это должно быть более надежным, хотя я не уверен, если это решит проблему. Вы можете просто получить пустой массив без ошибки.

Смежные вопросы