質問

I have a REST service that returns geo-coordinates that I'm consuming with a factory using $http in AngularJS. In order to display these coordinates as markers, I need to create google.maps.Marker object which take both a position and a google.maps.Map object.

I'm trying to figure out the best way to do these data transformations either in the factory, or as part of a transformResponse. Unfortunately, the AngularUI maps directive that I'm using stores the map on the local scope.

What is the best way to supply the Map object to either the factory or transformResponse?

役に立ちましたか?

解決

If you're adamant about your geocoordinates service returning Markers instead of geocoordinates, then you have two options that I can think of:

a) Pass the map to the geocoordinates service

angular.module('mapGuy', function($scope, geoService) {
  geoService.addMarkers($scope.map);
}).
factory('geoService', function($http) {
  var addMarkers = function(map) {
    $http.get('/path/to/geo/server').success(function(points) {
      angular.forEach(points, function(points) {
        new google.maps.Marker({
          map: map, position: new google.maps.LatLng(points.lat, points.long)
        })
      })
    });
  };

  return { addMarkers: addMarkers };
});

b) Stick the map on the module's $rootScope and inject $rootScope into the service

angular.module('mapGuy', function($scope, $rootScope, geoService) {
  $rootScope.map = $scope.map;
  geoService.addMarkers();
}).
factory('geoService', function($http, $rootScope) {
  var addMarkers = function() {
    $http.get('/path/to/geo/server').success(function(points) {
      angular.forEach(points, function(points) {
        new google.maps.Marker({
          map: $rootScope.map, position: new google.maps.LatLng(points.lat, points.long)
        })
      })
    });
  };

  return { addMarkers: addMarkers };
});

That's a rough sketch of what the code could look like. I'm pulling Google Maps API from memory, but hopefully this helps you get the idea.

I think the first option is preferable, but it's hard to say since you didn't provide a lot of context to work with.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top