Reputation: 1371
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:
while it should be:
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
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
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