0

I was playing around with angular to geo locate the address of the client using angular and some API services. I have gotten it to correctly locate the IP address but for some reason I haven't been able to perform a geo lookup. The API service is running fine and my URL seems to be good too.

'use strict';

angular.module('Zeus', [])
.controller('ZeusController', function ($scope, $http) {

    function fetchIP() {
        $http.get("http://ipv4.myexternalip.com/json")
            .then(function (response) {
                $scope.ip = response.data.ip;
            });
        return $scope.ip
    }

    var ip = String(fetchIP());

    function geoIP() {
            $http.get("https://freegeoip.net/json/" + String(ip))
                .then(function (response) {
                    $scope.country_code = response.data.country_code;
                });
        return $scope.country_code;
    }

    var latLon = geoIP();


});

I get the following error in my Chrome console:

Failed to load resource: the server responded with a status of 404 (OK)
https://freegeoip.net/json/undefined

The URL should definitely not be undefined because using the IP that angular returns the url returns the correct response in the web browser.

  • bro can u share the html as well coz i am getting this error GET https://freegeoip.net/json/undefined 404 () – DAOdAppDev Jul 30 '16 at 23:12

1 Answers1

3

That's because geoIP() has callback and you have to handle that callback

Like this

function geoIP() {
    return $http.get("https://freegeoip.net/json/" + String(ip))
        .then(function(response) {
            return response.data.country_code;
        });

}
var latLon;
geoIP().then(function(r) {
    latLon = r;
})
Anik Islam Abhi
  • 24,324
  • 8
  • 52
  • 74