Przemek Wojtas
Przemek Wojtas

Reputation: 1371

google maps api, get directions not passing full link and No 'Access-Control-Allow-Origin'

So I have a map and when user clicks on any marker I want to get a json. All variables have a value and when I manually put them in browser I get an response. At the moment I get:

XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/directions/json?origin=53.5411328&-2.1114581&destination=53.54027. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'my url of course' is therefore not allowed access.

And the link looks like this:

https://maps.googleapis.com/maps/api/directions/json?origin=53.541111&-2.1114894&destination=53.54027

while it should be:

https://maps.googleapis.com/maps/api/directions/json?origin=53.541111,-2.1114894&destination=53.54027,-2.1121799&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq65

Code:

marker.addListener('click', function() {
      var destinationLat = marker.getPosition().lat();
      var destinationLng = marker.getPosition().lng();
      console.log(lat);
      console.log(lng);
      console.log(destinationLng);
      console.log(destinationLat);
      var test = $.getJSON('https://maps.googleapis.com/maps/api/directions/json?origin='+lat+'',''+lng+'&destination='+destinationLat+'',''+destinationLng+'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq65', function(data) {
          console.log(test);
      });
      console.log(test);
    });
  }

Upvotes: 0

Views: 1071

Answers (2)

duncan
duncan

Reputation: 31922

The mistake's in this line:

var test = $.getJSON('https://maps.googleapis.com/maps/api/directions/json?origin='+lat+'',''+lng+'&destination='+destinationLat+'',''+destinationLng+'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq65', function(data) {

That should be:

var test = $.getJSON('https://maps.googleapis.com/maps/api/directions/json?origin='+lat+','+lng+'&destination='+destinationLat+','+destinationLng+'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq65', function(data) {

Upvotes: 1

xomena
xomena

Reputation: 32178

In order to avoid the CORS headers issue in your JavaScript code you should use a built-in Directions service of Maps JavaScript API.

https://developers.google.com/maps/documentation/javascript/directions

Replace your AJAX call with something similar to

directionsService.route({
    origin: new google.maps.LatLng(lat,lng),
    destination: new google.maps.LatLng(destinationLat,destinationLng),
    travelMode: 'DRIVING'
}, function(response, status) {
    if (status === 'OK') {
        //Process response here
    } else {
        window.alert('Directions request failed due to ' + status);
    }
}); 

Take a look at examples

https://developers.google.com/maps/documentation/javascript/examples/directions-simple

I hope this helps!

Upvotes: 0

Related Questions