2016-05-26 6 views
0

Ich versuche, den lat und Long von GetCurrentPosition zuzugreifen, so dass ich eine URL erstellen kann, um mit einer API zu verwenden. Dies funktioniert, wenn Sie es innerhalb der Funktion aufrufen oder wenn Sie eine Zeitüberschreitung für eine Warnung (außerhalb der Funktion) festlegen, da die aktuelle Position einige Minuten benötigt, um die Koordinaten zu bestimmen. Wie kann ich auf Coords-Variablen und/oder die URL-Adresse zugreifen? DankeAnruf Standortkoordinaten von außerhalb der Funktion

var coords1; 
    var coords2; 

    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 { 
     coords1 = e.coords.longitude; 
     coords1 = e.coords.latitude; 
    } 
    }); 
    } else { 

    alert('Please enable location services'); 
    } 


    var url = "http://www.mywebsite.com/api/return-latlong/"+coords1+"/"+coords2; 
    var xhr = Ti.Network.createHTTPClient({ 
    onload: function(e) { 
     // this function is called when data is returned from the server and available for use 
     // this.responseText holds the raw text return of the message (used for text/JSON) 
     // this.responseXML holds any returned XML (including SOAP) 
     // this.responseData holds any returned binary data 
     Ti.API.debug(this.responseText); 
     alert('success'); 
    }, 
    onerror: function(e) { 
     // this function is called when an error occurs, including a timeout 
     Ti.API.debug(e.error); 
     alert('error'); 
    }, 
    timeout:5000 // in milliseconds 
    }); 
    xhr.open("GET", url); 
    xhr.send(); // request is actually sent with this statement 


    alert(url); 

Antwort

0

nicht sicher, ob ich das Problem wirklich, aber Sie können eine Funktion für Ihre api HTTP-Anforderung verwenden, und es aufrufen, wenn Sie die aktuelle Position des coords erhalten, etwa wie folgt:

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.

Verwandte Themen