问题
I'm working on an app for fun which allows you to record routes you take. I'm using this to learn about the Google Maps API as well as Phonegap Build, so those are the tools I'm using here.
I made a rudimentary app which collects position data (lat,lng) into an array, then uses Google's API to display the results on a map. In the future I'd like to connect them with a line, allow comments, et cetera.
Here's what a drive around my neighborhood looks like:
Pretty neat. However, something's wrong here. A longer trip will crash the app when attempting to map that many coordinate points. Here in the docs, the options hash is described. Mine looks like this:
var options = { maximumAge: 1000, timeout: 3000, enableHighAccuracy: true };
I'm not sure I entirely understand the explanation. maximumAge
seems to mean that, barring new GPS or location data, it'll simply use the previous one, so setting it to 9999999 should make it so cached data is never used.
Timeout is trickier. It seems that location information is not a guarantee and therefore sometimes it'll throw an error. But does increasing that number make for a route with less plot points? Where can I find out about a GPS system works in tandem with a phone?
How to change those configurations for more accurate plotting with less points?
回答1:
you should use navigator.geolocation.watchPosition It returns the device's current position when a change in position is detected. When the device retrieves a new location, the geolocationSuccess callback executes with a Position object as the parameter. If there is an error, the geolocationError callback executes with a PositionError object as the parameter.
syntax
var watchId = navigator.geolocation.watchPosition(geolocationSuccess,
[geolocationError],
[geolocationOptions]);
Example
// onSuccess Callback
// This method accepts a `Position` object, which contains
// the current GPS coordinates
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Options: throw an error if no update is received every 30 seconds.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 3000 });
now, this way location will be captured only if device is moved so route with less plot points. change timeout as per your requirement.
clearwatch when you want to stop watching for changes to the device's location.
来源:https://stackoverflow.com/questions/36853475/how-to-make-a-phonegap-application-save-current-geolocation-less-often