【问题标题】:Using AngularJS factory to connect to google distance api using $resource使用 AngularJS 工厂使用 $resource 连接到谷歌距离 api
【发布时间】:2014-12-30 23:08:33
【问题描述】:

我想创建一个工厂,使用 $resource 从 google 的距离 api (https://developers.google.com/maps/documentation/distancematrix/) 中检索距离信息。

我已经剥离了参数以尝试让简单的服务正常工作..

这是我当前的代码:

VenuesAppServices.factory('VenueDistance', ['$resource',
function($resource){
    return $resource('http://maps.googleapis.com/maps/api/distancematrix/json', {}, {
        Distance: {method:'GET'}
    });
}]);

并称之为:

VenueDistance.Distance(function(results){
    alert(JSON.stringify(results));
},function(error){
    alert(JSON.stringify(error));
});

我希望返回以下内容:

{
"destination_addresses" : [],
"error_message" : "The 'sensor' parameter specified in the request must be set to either 'true' or 'false'.",
"origin_addresses" : [],
"rows" : [],
"status" : "REQUEST_DENIED"
}

但是我得到了 404 响应。

{"data":"","status":404,"config":{"transformRequest":[null],"transformResponse":[null],"method":"GET","url":"http://maps.googleapis.com/maps/api/distancematrix/json","headers":{"Accept":"application/json, text/plain, */*"}}}

如果您将 google api 换成类似 (http://api.geonames.org/postalCodeLookupJSON) 的 API。然后您会从该站点获得预期响应。

谁能告诉我为什么 google url 没有返回您从浏览器获得的结果?

【问题讨论】:

  • 这取决于谷歌是否遵循 angulars $resource 期望的约定
  • 实际发送的角度是什么?

标签: angularjs api distance ngresource


【解决方案1】:

我认为您不会发送诸如起点和终点之类的参数..

您需要通过 $resource 或 $http 服务发送 URL:

VenuesAppServices.factory('VenueDistance', ['$resource',function($resource){
return $resource('http://google.com/maps/api/distancematrix/json?origins=Bobcaygeon+ON|41.43206,-81.38992&destinations=Darling+Harbour+NSW+Australia|24+Sussex+Drive+Ottawa+ON|Capitola+CA', {}, { Distance: {method:'GET'}});}]);

VenuesAppServices.factory('VenueDistance', ['$resource',function($resource){
return $resource('http://google.com/maps/api/distancematrix/json?origins='+ origin +'&destinations='+ destination, {}, { Distance: {method:'GET'}});}]);

Google Maps API Documentation

【讨论】:

    【解决方案2】:

    可能是您收到跨域 javscript http 请求错误并对其进行字符串化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      相关资源
      最近更新 更多