Braydon Batungbacal
Braydon Batungbacal

Reputation: 1038

Javascript object method returning undefined?

Here is a quick question, I have the following method within an object, why is it returning undefined?

var getGeoLocation = function() {
            if (typeof(navigator.geolocation) != 'undefined') {
                var test = navigator.geolocation.getCurrentPosition(function(position) {
                    var lat = position.coords.latitude;
                    var lng = position.coords.longitude;
                    return(new google.maps.LatLng(lat, lng));    
                });
            }
        }
var testFunction = function() {alert(getGeoLocation()); // returns undefined?}

Upvotes: 2

Views: 7229

Answers (3)

Shyantanu
Shyantanu

Reputation: 681

function GetCurrentLocation()
            {
                if (navigator.geolocation) { 
                    navigator.geolocation.getCurrentPosition(function(position) {  

                                                             var point = new google.maps.LatLng(position.coords.latitude, 
                                                                                                position.coords.longitude);
alert(point);
                } 
                else {
                    alert('W3C Geolocation API is not available');
                }
            }

Use this code. It will give you the perfect result.

Upvotes: 0

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

It returns undefined because getGeoLocation does not return anything. Try this instead:

var getGeoLocation = function() {
            if (typeof(navigator.geolocation) != 'undefined') {
                var test = navigator.geolocation.getCurrentPosition(function(position) {
                    var lat = position.coords.latitude;
                    var lng = position.coords.longitude;
                    alert(new google.maps.LatLng(lat, lng));    
                });
            }
        }
var testFunction = function() {getGeoLocation()};

Upvotes: 2

James Allardice
James Allardice

Reputation: 166031

This is because navigator.geolocation.getCurrentPosition is asynchronous. The getGeoLocation function returns before the anonymous callback function passed to getCurrentPosition has been executed, and since the getGeoLocation function has no return statement, it returns undefined.

Move code that depends on the response from navigator.geolocation.getCurrentPosition inside the callback.

Upvotes: 7

Related Questions