Question

What i want to do is determining the location of user and then based on his location doing a request to Yelp API.

function getLocation()
  {
  if (navigator.geolocation)
    {
    var y = navigator.geolocation.getCurrentPosition(showPosition);
    return y;
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
 var y = position.coords.latitude + 
  "," + position.coords.longitude;
  return y;
  }


function doRequest(){

var terms = 'turkish';
var near = 'San+Francisco';
var ll = getLocation();
... }

I have tested the variable y, it gives true latitude and longitude and if i write self a coordinate in ll, request code does work.

The problem is, in this situation, my ll parameter seems "undefined" in the request and i cant receive any response from API . I don't understand what the problem is. Any idea?

Was it helpful?

Solution

The Geolocation API is asynchronous, so you have to wait for the data to be returned

function getLocation(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            callback({
                success : true, 
                result  : position.coords.latitude + "," + position.coords.longitude
            });
        });
    } else {
        callback({
            success : false, 
            result  : "Geolocation is not supported by this browser."
        });
    }
}

function doRequest() {
    var terms = 'turkish';
    var near = 'San+Francisco';
    getLocation(function(result) {
        if (result.success) {
            var y = result.result;

            // do something with y here
        }else{
            x.innerHTML = result.result;
        }
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top