谷歌地图directionsService.route没有解雇

时间:2014-07-02 14:19:53

标签: javascript google-maps directions

有人可以解释下面的代码发生了什么。 markerPosition& myPosition是谷歌地图LatLng对象。我把它们分解成了各自的点并用它们创造了新的物体。试图使这个东西工作,但我在DirectionsService.route请求中的警报永远不会弹出。谢谢Greg

function calcRoute(markerPosition, myPosition){
  startUserLat = myPosition.lat();
  startUserLng = myPosition.lng();
  endUserLat = markerPosition.lat();
  endUserLng = markerPosition.lng();

  var start = new google.maps.LatLng(startUserLat,startUserLng);
  var end = new google.maps.LatLng(endUserLat,endUserLng);
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
  };


  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      alert('stat OK');
    } else {alert('not OK');}
  });



}

完整代码......

<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var myLocation;

var userDirection, userPosition;

var origin1 = new google.maps.LatLng(55.930, -3.118);
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = new google.maps.LatLng(50.087, 14.421);


var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';

var locations = [
        ['A/P LA PAMPA',-0.0425 , -78.4558333333  , 1],
        ['A/P PUSUQUI'  , -0.0647222222 , -78.4655555556  , 2]        
      ];

function initialize() {
  var infoWindow = null;

  var opts = {
    center: new google.maps.LatLng(-1.2, -78.58),
    zoom: 6
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), opts);
  geocoder = new google.maps.Geocoder();
  var image = './images/theme-images/mascot_finder.png';
  infowindow = new google.maps.InfoWindow({
    content: "holding..."
  });

   for (i = 0; i < locations.length; i++) {
          var currentLatLong = new google.maps.LatLng(locations[i][1],locations[i][2]);
          marker = new google.maps.Marker({
          position: currentLatLong,
          map: map,
          icon: image
        });

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            var userDirection = marker.getPosition();
            var userPosition = myLocation.getPosition();
            infowindow.setContent(locations[i][0]);
            infowindow.open(map, marker);
            calcRoute(userDirection , userPosition);


          }
        })(marker, i));
      }


        getMyLocation();

}

      //directionsDisplay.setMap(map);

function calcRoute(markerPosition, myPosition){
  startUserLat = myPosition.lat();
  startUserLng = myPosition.lng();
  endUserLat = markerPosition.lat();
  endUserLng = markerPosition.lng();

  var start = (startUserLat,startUserLng);
  var end = (endUserLat,endUserLng);
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
  };


  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      alert('stat OK');
    } else {alert('not OK');}
  });



}



function calculateDistances() {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin1, origin2],
      destinations: [destinationA, destinationB],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
}

function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML = '';
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      addMarker(origins[i], false);
      for (var j = 0; j < results.length; j++) {
        addMarker(destinations[j], true);
        outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
            + ': ' + results[j].distance.text + ' in '
            + results[j].duration.text + '<br>';
      }
    }
  }
}

function addMarker(location, isDestination) {
  var icon;
  if (isDestination) {
    icon = destinationIcon;
  } else {
    icon = originIcon;
  }
  geocoder.geocode({'address': location}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      bounds.extend(results[0].geometry.location);
      map.fitBounds(bounds);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        icon: icon
      });
      markersArray.push(marker);
    } else {
      alert('Geocode was not successful for the following reason: '
        + status);
    }
  });
}

function deleteOverlays() {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}

function getMyLocation(){

  if (navigator.geolocation) {

           myLocation = navigator.geolocation.getCurrentPosition(function (position) {
               initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
               var myLocationArray = [position.coords.latitude , position.coords.longitude];
               map.setCenter(initialLocation);
               map.setZoom(10);            


               myLocation = new google.maps.Marker({
                 position: initialLocation, //new google.maps.LatLng(0, -78.58),
                 map: map,
               });
               myLocation.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
            });
       }
  return myLocation;
}

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

    </script>

1 个答案:

答案 0 :(得分:0)

您的完整代码与您在问题中发布的代码段不同。 API正在生成一个错误,告诉您错误:

Uncaught InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object

这是不正确的:

var start = (startUserLat, startUserLng);
var end = (endUserLat, endUserLng);

这些字符串可以是可以解析为地址的字符串,也可以是google.maps.LatLng对象,例如原始问题和我在评论中发布的fiddle

var start = new google.maps.LatLng(startUserLat, startUserLng);
var end = new google.maps.LatLng(endUserLat, endUserLng);

修复后,我收到此错误:

Uncaught TypeError: Cannot read property 'setDirections' of undefined 

你仍然错过了这个:

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

updated fiddle