0

How to Remove the this error

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource enter image description here

while calling google API Distance Matrix by jQuery

use this source

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=[API_KEY]", function(data, status){
      console.log("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>
Suhad Mendis
  • 55
  • 1
  • 10
  • 1
    Distance Matrix is available through the Google Maps Javascript API if you intend to use it client-side. You are calling the web service which is intended to be used server-side. – MrUpsidown Oct 01 '19 at 09:06

1 Answers1

1

This is cross origin issue. For security reasons browser blocks the requests made from different domain. You have to add 'Access-Control-Allow-Origin' header in your http request to specify that your domain has the access to the api you are hitting.

You can refer this question jQuery ajax request being block because Cross-Origin

Alternatively you can disable the same origin policy for chrome for testing. For reference Disable same origin policy in Chrome

Karan Kiri
  • 294
  • 2
  • 10
  • I have added that to my code but it doesn't work. It occurs the same error setHeader("Access-Control-Allow-Origin", "*"); – Suhad Mendis Oct 01 '19 at 06:05
  • You can try after disabling same origin policy for chrome. Please see https://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome – Karan Kiri Oct 01 '19 at 08:53