LifeLess LifeLess - 1 year ago 115
JSON Question

Angular.js googleMap API json Uncaught SyntaxError: Unexpected token :

I red all previous posts:
* i added : &callback=JSON_CALLBACK
* i also tried simple $http.get but it leads to: 'Access-Control-Allow-Origin'
* i also tried to define jsonpCallbackParam to'json_callback' from just callback and added format: 'jsonp'
*also tried to read documentation about $sce.trustAsResourceUrl(url) (well i didn't understand much :-(
On F12 -> source, i see that the required data is returned but on the console log i get Uncaught SyntaxError: Unexpected token .

please advise

var autoJsonpUrl = 'https://maps.googleapis.com/maps/api/distancematrix/json?region=il&origins=tel-aviv&destinations=jerusalem&key=AIzaSyD3xhn92KwStkZAg-rZueAFI1LooRLpND0' + '&callback=JSON_CALLBACK';

var options =
{
jsonpCallbackParam: 'json_callback',
cache: false
};

$http.jsonp(autoJsonpUrl, options).then(function (response) {
console.log(response);
});

Answer Source

Endpoint http://maps.googleapis.com/maps/api/distancematrix/ does not support JSONP, instead you could consider to utilize Google Maps JavaScript API as demonstrated below:

angular.module('mapApp', [])

    .controller("mapCtrl", function ($scope, $http) {
        $scope.routeInfo = null;
        var distanceMatrix = new google.maps.DistanceMatrixService();
        var distanceRequest = { region: "il", origins: ["tel-aviv"], destinations: ["jerusalem"], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC};
        distanceMatrix.getDistanceMatrix(distanceRequest, function (response, status) {
            if (status != google.maps.DistanceMatrixStatus.OK) {
                console.log('An error occured: ' + status);
            }
            else {
                $scope.$apply(function(){
                   $scope.routeInfo = response;    
                });
                
            }
        });
        
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<script src="app.js"></script>

<div ng-app="mapApp" ng-controller="mapCtrl">
    <pre>{{routeInfo | json}}</pre>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download