Skip to content Skip to sidebar Skip to footer

Call Location Coordinates From Outside The Function

I'm try to access the lat and long from getCurrentPosition so that I can create a URL to use with an API. This is working if you call it from within the function or if you set a ti

Solution 1:

not sure I really get your problem, but you can use a function for your api http request, and call it when you obtain the current position's coords, something like the following:

if (Ti.Geolocation.locationServicesEnabled) {
  Titanium.Geolocation.purpose = 'Get Current Location';
  Titanium.Geolocation.getCurrentPosition(function(e) {
    if (e.error) {
        Ti.API.error('Error: ' + e.error);
      } else {

        var latitude = e.coords.latitude;
        var longitude = e.coords.longitude;

        // make the http request when coords are set
        apiCall(latitude, longitude);
    }
  });
} else {
    alert('Please enable location services');
}

function apiCall(lat, long) {
  var url = "http://www.mywebsite.com/api/return-latlong/" + lat + "/" + long;
  alert(url);

  var xhr = Ti.Network.createHTTPClient({
    onload: function(e) {
        Ti.API.debug(this.responseText);
        alert('success');
    },
    onerror: function(e) {
        Ti.API.debug(e.error);
        alert('error');
    },
    timeout:5000  
  });

  xhr.open("GET", url);
  xhr.send(); 
}

Hth.


Post a Comment for "Call Location Coordinates From Outside The Function"