Error ( Access headers ) when sending AJAX request to get Google Maps' directions

前端 未结 1 1421
梦谈多话
梦谈多话 2021-01-28 11:53

I\'m trying to use the directions API of Google Maps to get directions and I\'m getting an error:

No \'Access-Control-Allow-Origin\' header is present on the req

相关标签:
1条回答
  • 2021-01-28 12:26

    After enabling the directions API and reading the documentation ( https://developers.google.com/maps/documentation/javascript/directions ) one can do something like this. This sets the map centre in chicago and gives directions from chicago to boston.

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    
    function initialize() {
      directionsDisplay = new google.maps.DirectionsRenderer();
      var chicago = new google.maps.LatLng(41.850033, -87.6500523);
      var mapOptions = {
          zoom:7,
          center: chicago
        }
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        directionsDisplay.setMap(map);
      }
    
      function calcRoute() {
      var start = 'Chicago';
      var end = 'Boston';
      var request = {
          origin:start,
          destination:end,
          travelMode: google.maps.TravelMode.DRIVING
      };
          directionsService.route(request, function(result, status) {
              if (status == google.maps.DirectionsStatus.OK) {
                  directionsDisplay.setDirections(result);
              }
          });
    }
    
    0 讨论(0)
提交回复
热议问题