Phonegap Geolocation:如果应用程序关闭,则跟踪位置

Posted

技术标签:

【中文标题】Phonegap Geolocation:如果应用程序关闭,则跟踪位置【英文标题】:Phonegap Geolocation: track position if app closed 【发布时间】:2012-07-21 17:43:10 【问题描述】:

我已经按照mobile.tutsplus上的教程进行操作

全部运行。

但是:如果我关闭应用程序或打开设备锁定,跟踪将停止。 我想为我的个人慢跑跟踪器添加一些附加功能,所以我希望跟踪继续进行。

恐怕只有 Objective-C 中的纯原生 App 才有可能。

有什么想法吗?

【问题讨论】:

【参考方案1】:

不确定是否要在后台运行它...但我浏览了相同的教程并且不得不关闭睡眠模式才能使其工作。我仍然无法运行该教程。第一个轨道运行完美,但任何后续轨道都不会运行。系统冻结。我在startTracking_stop 函数中找到了删除var 的建议。还是不行。然后我添加了一个警报,发现该对象没有被传递...我收到null 消息。

你是如何让这个程序在第一条轨道之外运行的?

【讨论】:

本教程的 var-scope 中有一些小错误。今天晚上我会给你我的代码。它仍在运行。【参考方案2】:
<!DOCTYPE html>
<html>
  <head>
  <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
      <meta charset="utf-8">


    <link rel="stylesheet" href="css/themes/default/jquery.mobile-1.1.0.min.css" />
    <link rel="stylesheet" href="css/author.css" />
    <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=<your CODEhere>&sensor=false"></script>

    <script type="text/javascript" src="js/libs/json2.js"></script>
    <script type="text/javascript" src="js/libs/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="js/libs/jquery.mobile-1.1.0.min.js"></script>
    <script type="text/javascript" src="js/plugins/countdown.js"></script>

    <script type="text/javascript" src="js/exercisetracker.js"></script>
  </head>
  <body onload="onBodyLoad()">

  <!-- BEGIN home -->
    <div data-role="page" id="home">
      <div data-role="header">
        <h1>Home</h1>
        <div data-role="navbar">
          <ul>
            <li><a href="#home" data-transition="none" data-icon="home">Home</a></li>
            <li><a href="#startTracking" data-transition="none" data-icon="plus">Track Workout</a></li>
            <li><a href="#history" data-transition="none" data-icon="star">History</a></li>
          </ul>
        </div>
      </div>

      <div data-role="content">
        <div data-role="controlgroup">
          <button id="home_network_button" data-icon="check">Internet Access Enabled</button>
          <button id="home_clearstorage_button">Clear local storage</button>
          <button id="home_seedgps_button">Load Seed GPS Data</button>
        </div>
      </div>
    </div>
  <!-- EOF home -->

  <!-- BEGIN startTracking -->
    <div data-role="page" id="startTracking">
      <div data-role="header">
        <h1>Track Workout</h1>

        <div data-role="navbar">
          <ul>
            <li><a href="#home" data-transition="none" data-icon="home">Home</a></li>
            <li><a href="#startTracking" data-transition="none" data-icon="plus">Track Workout</a></li>
            <li><a href="#history" data-transition="none" data-icon="star">History</a></li>
          </ul>
        </div>
      </div>

      <div data-role="content">
        <p id="startTracking_status"></p>
        <div data-role="fieldcontain" class="ui-hide-label">
          <label for="track_id">Track ID/Name:</label>
          <input type="text" name="track_id" id="track_id" placeholder="Workout ID/Name"/>
        </div>

        <button data-role="button" id="startTracking_start">Start Tracking</button>
        <button data-role="button" id="startTracking_stop">Stop Tracking</button>

        <p id="startTracking_debug"></p>

      </div>
    </div>
  <!-- EOF startTracking -->

  <!-- BEGIN history -->
  <div data-role="page" id="history">
    <div data-role="header">
      <h1>History</h1>

      <div data-role="navbar">
        <ul>
          <li><a href="#home" data-transition="none" data-icon="home">Home</a></li>
          <li><a href="#startTracking" data-transition="none" data-icon="plus">Track Workout</a></li>
          <li><a href="#history" data-transition="none" data-icon="star">History</a></li>
        </ul>
      </div>
    </div>

    <div data-role="content">
      <p id="tracks_recorded"></p>
      <ul data-role="listview" id="history_tracklist">

      </ul>
    </div>
  </div>
  <!-- EOF history -->

  <!-- BEGIN track_info -->
  <div data-role="page" id="track_info">

    <div data-role="header">
      <h1>Viewing Single Workout</h1>

      <div data-role="navbar">
        <ul>
          <li><a href="#home" data-transition="none" data-icon="home">Home</a></li>
          <li><a href="#startTracking" data-transition="none" data-icon="plus">Track Workout</a></li>
          <li><a href="#history" data-transition="none" data-icon="star">History</a></li>
        </ul>
      </div>
    </div>

    <div data-role="content">
      <p id="track_info_info"></p>

      <div id="map_canvas" style="position:absolute;bottom:0;left:0;width:100%;height:300px;"></div>

    </div>
  </div>
  <!-- EOF track_info -->
  </body>
</html>

现在是 JS 文件

function gps_distance(lat1, lon1, lat2, lon2)

  // http://www.movable-type.co.uk/scripts/latlong.html
  var R = 6371; // km
  var dLat = (lat2-lat1) * (Math.PI / 180);
  var dLon = (lon2-lon1) * (Math.PI / 180);
  var lat01 = lat1 * (Math.PI / 180);
  var lat02 = lat2 * (Math.PI / 180);

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat01) * Math.cos(lat02);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;

  return d;


function onBodyLoad() 
  document.addEventListener("deviceready", onDeviceReady, false);

  var track_id = ''; // Name/ID of the exercise
  var watch_id;    // ID of the geolocation
  var tracking_data = []; // Array containing GPS position objects

  $("#startTracking_start").live('click', function()

    // Start tracking the User
    watch_id = navigator.geolocation.watchPosition(

        // Success
        function(position)
          tracking_data.push(position);
          console.log(tracking_data);
        ,

        // Error
        function(error)
          console.log(error);
        ,

        // Settings
         frequency: 3000, enableHighAccuracy: true );

    // Tidy up the UI
    track_id = $("#track_id").val();

    $("#track_id").hide();
    $("#startTracking_status").html("Tracking workout: <strong>" + track_id + "</strong>");

    return;
  );

  $("#startTracking_stop").live('click', function()

    // Stop tracking the user
    navigator.geolocation.clearWatch(watch_id);

    // Save the tracking data
    window.localStorage.setItem(track_id, JSON.stringify(tracking_data));

    // Reset watch_id and tracking_data
    watch_id = null;
    tracking_data = null;

    // Tidy up the UI
    $("#track_id").val("").show();
    $("#startTracking_status").html("Stopped tracking workout: <strong>" + track_id + "</strong>");
  );

  $("#home_clearstorage_button").live('click', function()
    window.localStorage.clear();
    console.log('LocalStorage cleared');
  );

  $("#home_seedgps_button").live('click', function()
    window.localStorage.setItem('Sample block', '["timestamp":1335700802000,"coords":"heading":null,"altitude":null,"longitude":170.33488333333335,"accuracy":0,"latitude":-45.87475166666666,"speed":null,"altitudeAccuracy":null,"timestamp":1335700803000,"coords":"heading":null,"altitude":null,"longitude":170.33481666666665,"accuracy":0,"latitude":-45.87465,"speed":null,"altitudeAccuracy":null,"timestamp":1335700804000,"coords":"heading":null,"altitude":null,"longitude":170.33426999999998,"accuracy":0,"latitude":-45.873708333333326,"speed":null,"altitudeAccuracy":null,"timestamp":1335700805000,"coords":"heading":null,"altitude":null,"longitude":170.33318333333335,"accuracy":0,"latitude":-45.87178333333333,"speed":null,"altitudeAccuracy":null,"timestamp":1335700806000,"coords":"heading":null,"altitude":null,"longitude":170.33416166666666,"accuracy":0,"latitude":-45.871478333333336,"speed":null,"altitudeAccuracy":null,"timestamp":1335700807000,"coords":"heading":null,"altitude":null,"longitude":170.33526833333332,"accuracy":0,"latitude":-45.873394999999995,"speed":null,"altitudeAccuracy":null,"timestamp":1335700808000,"coords":"heading":null,"altitude":null,"longitude":170.33427333333336,"accuracy":0,"latitude":-45.873711666666665,"speed":null,"altitudeAccuracy":null,"timestamp":1335700809000,"coords":"heading":null,"altitude":null,"longitude":170.33488333333335,"accuracy":0,"latitude":-45.87475166666666,"speed":null,"altitudeAccuracy":null]');

  );

  // When the user views the history page
  $('#history').live('pageshow', function () 

    // Count the number of entries in localStorage and display this information to the user
    tracks_recorded = window.localStorage.length;
    $("#tracks_recorded").html("<strong>" + tracks_recorded + "</strong> workout(s) recorded");

    // Empty the list of recorded tracks
    $("#history_tracklist").empty();

    // Iterate over all of the recorded tracks, populating the list
    for(i=0; i<tracks_recorded; i++)
        $("#history_tracklist").append("<li><a href='#track_info' data-ajax='false'>" + window.localStorage.key(i) + "</a></li>");
    

    // Tell jQueryMobile to refresh the list
    $("#history_tracklist").listview('refresh');

  );

  $("#history_tracklist li a").live('click', function()

    $("#track_info").attr("track_id", $(this).text());

  );

// When the user views the Track Info page
  $('#track_info').live('pageshow', function()

    // Find the track_id of the workout they are viewing
    var key = $(this).attr("track_id");

    // Update the Track Info page header to the track_id
    $("#track_info div[data-role=header] h1").text(key);

    // Get all the GPS data for the specific workout
    var data = window.localStorage.getItem(key);

    console.log('Saved Storage: ' + data);

    // Turn the stringified GPS data back into a JS object
    data = JSON.parse(data);

    // Calculate the total time taken for the track
    start_time = new Date(data[0].timestamp).getTime();
    end_time = new Date(data[data.length-1].timestamp).getTime();

    total_time_ms = end_time - start_time;
    total_time_s = total_time_ms / 1000;

    final_time_m = Math.floor(total_time_s / 1000);
    final_time_s = total_time_s - (final_time_m * 60);

    // Calculate the total distance travelled
    total_km = 0;

    for(i = 0; i < data.length; i++)

      if(i == (data.length - 1))
        break;
      

      total_km += gps_distance(data[i].coords.latitude, data[i].coords.longitude, data[i+1].coords.latitude, data[i+1].coords.longitude);
    

    total_km_rounded = total_km.toFixed(2);

    // Display total distance and time
    $("#track_info_info").html('Travelled <strong>' + total_km_rounded + '</strong> km in <strong>' + final_time_m + 'm</strong> and <strong>' + final_time_s + 's</strong>');

    console.log('Write Info')

    // Set the initial Lat and Long of the Google Map
    var myLatLng = new google.maps.LatLng(data[0].coords.latitude, data[0].coords.longitude);

    // Google Map options
    var myOptions = 
      zoom: 15,
      center: myLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    ;

    // Create the Google Map, set options
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var trackCoords = [];

    // Add each GPS entry to an array
    for(i=0; i<data.length; i++)
      trackCoords.push(new google.maps.LatLng(data[i].coords.latitude, data[i].coords.longitude));
    

    // Plot the GPS entries as a line on the Google Map
    var trackPath = new google.maps.Polyline(
      path: trackCoords,
      strokeColor: "#FF0000",
      strokeOpacity: 1.0,
      strokeWeight: 2
    );

    // Apply the line to the map
    trackPath.setMap(map);

  );







function onDeviceReady() 

  if ( navigator.network.connection.type == Connection.NONE ) 
    $('#home_network_button').text('No Internet Access')
        .attr('data-icon', 'delete')
        .button('refresh');
  

【讨论】:

以上是关于Phonegap Geolocation:如果应用程序关闭,则跟踪位置的主要内容,如果未能解决你的问题,请参考以下文章

phonegap android中navigator.geolocation.getCurrentLocation的奇怪行为

Phonegap Geolocation API 总是得到错误代码 3

PhoneGap/Cordova 将 GeoLocation 从 localStorage vars 推送到 MySQL

速度坐标在 GeoLocation PhoneGap 中显示空值

PhoneGap Build 6.3.0 geolocation getCurrentPosition 在IOS上慢

Phonegap/Cordova Geolocation 不适用于 Android 4.0+,但适用于所有其他平台