【问题标题】:Call location coordinates from outside the function从函数外部调用位置坐标
【发布时间】:2016-05-26 16:15:08
【问题描述】:

我正在尝试从 getCurrentPosition 访问经纬度,以便我可以创建一个与 API 一起使用的 URL。如果您从函数内部调用它或者在警报(函数外部)上设置超时,这将起作用,因为当前位置需要一些时间来确定坐标。如何访问坐标变量和/或 URL 之一?谢谢

  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);

【问题讨论】:

    标签: javascript ios titanium appcelerator


    【解决方案1】:

    不确定我是否真的明白你的问题,但你可以为你的 api http 请求使用一个函数,并在你获得当前位置的坐标时调用它,如下所示:

    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(); 
    }
    

    第一次。

    【讨论】:

      猜你喜欢
      • 2017-09-27
      • 2021-05-31
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2014-10-01
      • 2012-05-27
      • 2015-03-02
      相关资源
      最近更新 更多