1

How do I get JSON from google directions api using jQuery?

I need to make the requests as "eithel" has mentioned in above link because I am making multiple requests and I need the responses for all and need to continue. If I use requests for services from clientside, there will be delays from one to next response and as it would be asynchronous, by the time I get the responses, my next set of codes would have been executed and which I really don't want to happen. But if I use requests for services from serverside through ajax, I can make it synchronous and workout. I could do that for "geocode" but for "distancematrix", I am getting an error "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access". Is there any workaround, please help me with this.

I am trying to find the distance between addresses and put them in matrix, with 2 ways, one is "requests for services from clientside"

window.findDistance = function(){
var distance = 0;
var matrixLength = address.length;
distanceArray = new Array(matrixLength);
for (var i = 0; i < matrixLength; i++) 
{
    distanceArray[i] = new Array(matrixLength);
}

for (var i=0;i<address.length;i++)
{
    for (var j=0;j<address.length;j++)
    {
        if(i==j)
        {
            distanceArray[i][j] = 0;
        }
        else
        {
            var directionsService = new google.maps.DirectionsService();
            var request = {
                    origin:address[i],
                    destination:address[j],
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                    };
            directionsService.route(request, function(response, status)
            {
                if (status == google.maps.DirectionsStatus.OK)
                {
                    distance = response.routes[0].legs[0].distance.text;
                    distanceArray[x][y] = distance;
                }
            });

        }
    }
}
}

The above code is not synchronous, j is incremented and gone for second iteration before I get the distance. How can I use callback here so that next iteration should happen only after getting the distance?

The second way is, "requests for services from serverside"

window.findDistance = function(){
var distance = 0;
var matrixLength = address.length;
distanceArray = new Array(matrixLength);
for (var i = 0; i < matrixLength; i++) 
{
    distanceArray[i] = new Array(matrixLength);
}
for (var i=0;i<address.length;i++)
{
    for (var j=0;j<address.length;j++)
    {
        if(i==j)
        {
            distanceArray[i][j] = 0;
        }
        else
        {
            var origin = address[i].replace(/ /g,"+");
            var destination = address[j].replace(/ /g,"+");
            var distanceUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+origin+"&destinations="+destination+"";

            $.ajax({
            type: "GET",
            async: false,
            url: distanceUrl,
            success: function(data) {
                var locJSON=new Array();        
                locJSON=eval(data);
                distance = locJSON.response.routes[0].legs[0].distance.text;
                }   
            });
            distanceArray[i][j] = distance;
        }
    }
}
}

I don't mind making it synchronous by async:false but this is giving me an error, "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access". How can I implement JSONP or CORS for this or server-side proxy?

I am completely new for all these WORDS.

Community
  • 1
  • 1
Punith G
  • 31
  • 6

1 Answers1

0

Firstly, never use async: false. Synchronous requests block the UI from updating until the request completes, which is terrible for the user. It looks like the browser has frozen for that period and for that reason it why it is considered incredibly bad practice.

Instead, assuming that your requests must be executed in a specific order, chain them so that the next request occurs in the callback of the previous one.

Secondly, regarding the error you get from one of the requests:

For "distancematrix", I am getting an error "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access"

This means that the request to this domain is being blocked by the Same Origin Policy. If the receiving server supports it you should use JSONP or CORS. If they do not, you will need to use a server-side proxy to make the request.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339