Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getJSON Google Distance Matrix API - Syntax Error

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?

like image 557
Harry Avatar asked Sep 20 '12 08:09

Harry


2 Answers

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.

like image 52
Onur Yıldırım Avatar answered Nov 05 '22 09:11

Onur Yıldırım


You should never call Google Maps webservices directly from client-side code*. Simply JSONP (ie json with 'callback') is NOT supported.

You need to use the Distance Matrix Service as part of the Google Maps Javascript API https://developers.google.com/maps/documentation/javascript/services#distance_matrix

  • The webservices are for accessing the APIs where the Javascript API cant run - ie in servers.
like image 44
barryhunter Avatar answered Nov 05 '22 10:11

barryhunter