Dhuum
Dhuum

Reputation: 35

Trying to geocode with Google Geocode API through Angular controller, values are undefined

So I have this Cordova App using AngularJS. I have built several controllers for it and I have had zero issues so far, but now trying to geocode address provided by the API we have built for the client, all I can seem to get is undefined when trying to access key/value pairs.

The purpose of the console.log here is just to make sure that the object is being correctly parsed and that I can access the content (I use a live-reload server while debugging for testing), the actual content is loaded form an HTML template inside the App.

It's been a few days in with this issue and I can;t get it to work, please lend me a hand with this one!

.controller('StayDetailCtrl', function($scope, $http, $stateParams) {
stayId = $stateParams.stayId
$scope.geodata = [];

$http.get('http://api.vllapp.com/staydetail/' + stayId)
    .then(function(result) {
        $scope.staydetails = result.data;

$http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + $scope.staydetails.address + '&key=AIzaSyBZVOSPh0Z4mv9jljJWzZNSug6upuec7Sg')
    .then(console.log($scope.staydetails.address))
        .then(function(result) {
            $scope.geodata = result.data;
    })
    .then(console.log($scope.geodata.geometry.location.lat))
});

Note: this bit is loaded on another controller which works just fine, which is whence the template gets all the other data to build itself.

$scope.staydetails = [];

Thanks in advance!

Edited the piece of code to make it synchronous, to no avail :/

Upvotes: 2

Views: 3569

Answers (1)

Aaron Saunders
Aaron Saunders

Reputation: 33335

Not sure if I understand the question, but I think you might find the code below helpful.

http://codepen.io/aaronksaunders/pen/ogajKX?editors=101

.controller('MainCtrl', function($scope,$http) {
  var address ="1334 Emerson St, NE Washington DC";

  $scope.geodata = {};
  $scope.queryResults = {};
  $scope.queryError = {};

  $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + 
            address + '&key=AIzaSyBZVOSPh0Z4mv9jljJWzZNSug6upuec7Sg')
    .then(function(_results){
       console.log(_results.data);
       $scope.queryResults = _results.data.results;
       $scope.geodata = $scope.queryResults[0].geometry
     }, 
     function error(_error){
        $scope.queryError = _error;
     })
});

Upvotes: 3

Related Questions