wordSmith
wordSmith

Reputation: 3183

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

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 requested resource. Origin 'http://irfanknow.com' is therefore not allowed access.

I've tried using https are the protocol and jsonp as the data type, but neither seem to fix it. What am I doing wrong?

Here is my code:

$.ajax({
    url: 'https://maps.googleapis.com/maps/api/directions/json?origin='+encodeURI(from)+'&destination='+encodeURI(to)+'&key=AIzaSyA-DmsaUVTWZgzqd43J5lMWIgUcIiIfIlo',
    dataType: 'json',
    jsonp: 'callback',
    method: 'GET',
    success: function(directionsResults){
        console.log(directionsResults);
                            }
                                            });

Upvotes: 0

Views: 580

Answers (1)

wordSmith
wordSmith

Reputation: 3183

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);
          }
      });
}

Upvotes: 2

Related Questions