getJSON Google Distance Matrix API - Syntax Error

Harry picture Harry · Sep 20, 2012 · Viewed 7.4k times · Source

I am using CoffeeScript to do a getJSON request:

$.getJSON(
    "http://maps.googleapis.com/maps/api/distancematrix/json?callback=?"
    origins: origin
    destinations: destinations
    sensor: false
    success: (data) -> 
        console.log data
   error: (data) ->
        console.log data
  'json'
)

URL is:

http://maps.googleapis.com/maps/api/distancematrix/json?callback=?&origins=-25.8350643,28.1636066&destinations=-25.551836,%2028.423075|-25.218503,%2027.923075|&sensor=false

If you put that in your browser it will return the JSON, but the ajax request just tells me:

Uncaught SyntaxError: Unexpected token: 

Any ideas?

Answer

Onur Yıldırım picture Onur Yıldırım · May 26, 2014

That endpoint does not support (JSONP) callbacks.
You should do it Google's way:

    var distanceService = new google.maps.DistanceMatrixService();
    distanceService.getDistanceMatrix({
        origins: ['Istanbul, Turkey'],
        destinations: ['Ankara, Turkey'],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        durationInTraffic: true,
        avoidHighways: false,
        avoidTolls: false
    },
    function (response, status) {
        if (status !== google.maps.DistanceMatrixStatus.OK) {
            console.log('Error:', status);
        } else {
            console.log(response);
        }
    });

See documentation here.