Frederik Witte
Frederik Witte

Reputation: 1345

Angular JS $http request?

I am trying to make a $http request with angular js to get a json object from google maps.

$http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city' ] + ',Deutschland' + '&sensor=true').success(function(mapData) {
                        angular.extend($scope, mapData);
    });

I read that I need to "inject" $http first, but I just cant get my head around how that works? I tried to do something like this:

angular.module('wmw', [])
.run(['$scope', '$http', function($scope, $http){
    function getTargetCords(data, $scope, $http) {
        var city = data[ 'city' ];
        return $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city' ] + ',Deutschland' + '&sensor=true').success(function(mapData) {
                    angular.extend($scope, mapData);
        });
    }
}]);

But in this case it is saying "getTargetCords is not defined" when I am trying to use it outside of this. I tried multiple different solutions and cant get my head around how to get this to work.

Edit: I think the reason why I need this function is maybe quite confusing, so here is my other code:

var onSuccess = function(position) {
    currentLat = position.coords.latitude ;
    currentLng = position.coords.longitude;
    var thecoords = [];
    $('#filter-list').empty();
    for(i = 0; i<locations.length;i++){
            thecoords = getTargetCords(locations[i]);
            var distance = calculateDistance(currentLat, currentLng, thecoords[0], thecoords[1]);
            addItemToList(locations[i], distance);
    }   
};

// onError Callback receives a PositionError object
function onError(error) {
    alert('Aktueller Standort konnte nicht berechnet werden');
}

navigator.geolocation.getCurrentPosition(onSuccess, onError);

We have different locations and I need the distance for each location.

Please note: as I didn't quite finish the angular part, the "thecoords[0]", "thecoods[1]" are obviously wrong values right now

Upvotes: 1

Views: 1368

Answers (1)

Dayan
Dayan

Reputation: 8031

UPDATE 2

http://pastebin.com/WUuYFAnX

When we wish to call AngularJS code from within a legacy app, think of the AngularJS code as being a small application existing within a protected container in your legacy application; You cannot make calls to it directly, but you can make remote calls.

You can use the Id of the HTML element where the Controller resides. (Not recommended) but you can do the following:

HTML Changes, We need ng-controller and ng-app

<html ng-app="wmw">
<body ng-controller="MainCtrl" id="MainCtrlId">
   ...
</body>
</html>

Angular Code & Native JS

var app = angular.module('wmw', []);

    app.controller('MainCtrl', function ($scope, $http) {

               $scope.getTargetCords = function (data) {

               $http.get(data).success(function (response) {
                    var responseData = JSON.parse(response);
                    console.log(responseData);
               });
            };
    });



function getCords() {
    var city = activeDest['city'];
    var destUrl = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' + activeDest['street'] + ',' + activeDest['city'] + ',Deutschland' + '&sensor=true';

    var MyAngularScope = angular.element($("#MainCtrlId")).scope();
    //Now call your angular method.
    MyAngularScope.getTargetCords(destUrl);
}

For more details on this technique look at this JSFiddle Example.

It is strongly recommended that you redo the application to work within the Angular Ecosystem instead of doing the above.

Here is a simple angular setup, separate Angular Controllers into their on JSfiles and Import them in your HTML like you would with any other JS file.

var app = angular.module('wmw', []);
app.controller('YourCtrlName', function ($scope, $http) {

    //Inside your controller you can define your "scope functions".
    $scope.getTargetCords= function(){

          $http.get('urlToGet').success(function(response) {
               var responseData = JSON.parse(response);
               console.log(responseData); 
          });

    };
});

Now in your HTML You can have something like this:

<div ng-app="wmw">
  <div ng-controller="YourCtrlName">
      <button ng-click="getTargetCords()">GET DATA</button>
  </div>
</div>

You were receiving:

getTargetCords is not defined

Because you were attempting to access an Angular controller method from outside the Angular Application.

Upvotes: 1

Related Questions