本文介绍了Phonegap地理位置:如果应用关闭,跟踪位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已遵循



所有运行。



/ strong>如果我关闭了应用程序或打开设备锁定跟踪停止。
我想让我的个人慢跑跟踪器有一些额外的功能,所以我想让跟踪继续。



我恐怕只能使用

解决方案

<$>



p $ p> <!DOCTYPE html>
< html>
< head>
< title>< / title>

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


< link rel =stylesheethref =css / themes / default / jquery.mobile-1.1.0.min.css/>
< link rel =stylesheethref =css / author.css/>
< script type =text / javascriptcharset =utf-8src =cordova-1.9.0.js>< / script>

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

< script type =text / javascriptsrc =js / libs / json2.js>< / script&
< script type =text / javascriptsrc =js / libs / jquery-1.7.2.min.js>< / script>
< script type =text / javascriptsrc =js / libs / jquery.mobile-1.1.0.min.js>< / script>
< script type =text / javascriptsrc =js / plugins / countdown.js>< / script>

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

<! - BEGIN首页 - >
< div data-role =pageid =home>
< div data-role =head>
< h1>首页< / h1>
< div data-role =navbar>
< ul>
< li>< a href =#homedata-transition =nonedata-icon =home>首页< / a>< / li>
< li>< a href =#startTrackingdata-transition =nonedata-icon =plus> Track Workout< / a>< / li>
< li>< a href =#historydata-transition =nonedata-icon =star>历史< / a>< / li&
< / ul>
< / div>
< / div>

< div data-role =content>
< div data-role =controlgroup>
< button id =home_network_buttondata-icon =check>启用互联网< / button>
< button id =home_clearstorage_button>清除本地存储空间< / button>
< button id =home_seedgps_button>载入种子GPS数据< / button>
< / div>
< / div>
< / div>
<! - EOF主页 - >

<! - BEGIN startTracking - >
< div data-role =pageid =startTracking>
< div data-role =header>
< h1>跟踪锻炼< / h1>

< div data-role =navbar>
< ul>
< li>< a href =#homedata-transition =nonedata-icon =home>首页< / a>< / li>
< li>< a href =#startTrackingdata-transition =nonedata-icon =plus> Track Workout< / a>< / li>
< li>< a href =#historydata-transition =nonedata-icon =star>历史< / a>< / li&
< / ul>
< / div>
< / div>

< div data-role =content>
< p id =startTracking_status>< / p>
< div data-role =fieldcontainclass =ui-hide-label>
< label for =track_id>曲目ID /名称:< / label>
< input type =textname =track_idid =track_idplaceholder =Workout ID / Name/>
< / div>

< button data-role =buttonid =startTracking_start>开始跟踪< / button>
< button data-role =buttonid =startTracking_stop>停止跟踪< / button>

< p id =startTracking_debug>< / p>

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

<! - BEGIN history - >
< div data-role =pageid =history>
< div data-role =header>
< h1>历史< / h1>

< div data-role =navbar>
< ul>
< li>< a href =#homedata-transition =nonedata-icon =home>首页< / a>< / li>
< li>< a href =#startTrackingdata-transition =nonedata-icon =plus> Track Workout< / a>< / li>
< li>< a href =#historydata-transition =nonedata-icon =star>历史< / a>< / li&
< / ul>
< / div>
< / div>

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

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

<! - BEGIN track_info - >
< div data-role =pageid =track_info>

< div data-role =header>
< h1>查看单一锻炼< / h1>

< div data-role =navbar>
< ul>
< li>< a href =#homedata-transition =nonedata-icon =home>首页< / a>< / li>
< li>< a href =#startTrackingdata-transition =nonedata-icon =plus> Track Workout< / a>< / li>
< li>< a href =#historydata-transition =nonedata-icon =star>历史< / a>< / li&
< / ul>
< / div>
< / div>

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

< div id =map_canvasstyle =position:absolute; bottom:0; left:0; width:100%; height:300px;>< / div&

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

现在JS-File

  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 / * 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 =''; //练习的名称/ ID
var watch_id; //地理位置的ID
var tracking_data = []; //包含GPS位置对象的数组

$(#startTracking_start)live('click',function(){

//开始跟踪用户
watch_id = navigator.geolocation.watchPosition(

//成功
函数(位置){
tracking_data.push(position);
console.log(tracking_data) ;
},

//错误
函数(错误){
console.log(错误);
},

//设置
{frequency:3000,enableHighAccuracy:true});

//整理UI
track_id = $(#track_id)。val );

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

return;
});

$(#startTracking_stop)。live('click',function(){

//停止跟踪用户
navigator.geolocation.clearWatch watch_id);

//保存跟踪数据
window.localStorage.setItem(track_id,JSON.stringify(tracking_data));

//重置watch_id和tracking_data
watch_id = null;
tracking_data = null;

//整理UI
$(#track_id)。 ();
$(#startTracking_status)。html(Stopped tracking workout:< strong>+ track_id +< / strong>);
});

$(#home_clearstorage_button)。live('click',function(){
window.localStorage.clear();
console.log );
});

$(#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, height: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, 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,longitude:170.33526833333332,accuracy:0,latitude: - 45.873394999999995,speed:null,altitudeAccuracy:null}},{timestamp:1335700808000,coords :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} );

});

//当用户查看历史页面
$('#history')。live('pageshow',function(){

// Count localStorage中的条目数,并将此信息显示给用户
tracks_recorded = window.localStorage.length;
$(#tracks_recorded)。html(< strong>+ tracks_recorded +< ; / strong>录制的锻炼);

//清空录制轨道的列表
$(#history_tracklist)。empty();

//迭代所有记录的轨道,填充列表
for(i = 0; i< tracks_recorded; i ++){
$(#history_tracklist)。append(< li> ;< a href ='#track_info'data-ajax ='false'>+ window.localStorage.key(i)+< / a>< / li>);
}

//通过jQueryMobile刷新列表
$(#history_tracklist)listview('refresh');

});

$(#history_tracklist li a)。live('click',function(){

$(#track_info)。attr $(this).text());

});

//当用户查看跟踪信息页面
$('#track_info')。live('pageshow',function(){

找到他们正在查看的锻炼的track_id
var key = $(this).attr(track_id);

//将Track Info页面标题更新为track_id
$(#track_info div [data-role = header] h1)。text(key);

//获取特定锻炼的所有GPS数据
var data = window .localStorage.getItem(key);

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

//将字符串化的GPS数据转换回JS对象
data = JSON.parse(data);

//计算轨道的总时间
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);

//计算总行程距离
total_km = 0;

for(i = 0; i
if(i ==(data.length - 1)){
打破;
}

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

//显示总距离和时间
$(#track_info_info)。html('Traveled< strong>'+ total_km_rounded +'< / strong> km in< strong> ;'+ final_time_m +'m< / strong>和< strong>'+ final_time_s +'s< / strong>');

console.log('Write Info')

//设置Google Map的初始Lat和Long
var myLatLng = new google.maps.LatLng (data [0] .coords.latitude,data [0] .coords.longitude);

// Google地图选项
var myOptions = {
zoom:15,
center:myLatLng,
mapTypeId:google.maps.MapTypeId.ROADMAP
};

//创建Google地图,设置选项
var map = new google.maps.Map(document.getElementById(map_canvas),myOptions);

var trackCoords = [];

//将每个GPS条目添加到数组
for(i = 0; i trackCoords.push(new google.maps.LatLng (data [i] .coords.latitude,data [i] .coords.longitude));
}

//在Google Map上将GPS条目作为一条线绘制
var trackPath = new google.maps.Polyline({
path:trackCoords,
strokeColor:#FF0000,
strokeOpacity:1.0,
strokeWeight:2
});

//将该行应用到地图
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');
}
}


i've followed the tutorial on mobile.tutsplus

All runs.

But: If I closed the app or turn on the device lock the tracking stops.I want to make my personal jogging tracker with some additional features so i want that the tracking goes on.

I'm afraid that is only possible with a pure native App in Objective-C.

Any Ideas?

解决方案
<!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>

And now the JS-File

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地理位置:如果应用关闭,跟踪位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:52