-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp3.js
More file actions
executable file
·347 lines (316 loc) · 9.15 KB
/
App3.js
File metadata and controls
executable file
·347 lines (316 loc) · 9.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// App.js
import React, { useState, useEffect, useRef } from 'react';
import {
SafeAreaView,
StyleSheet,
Text,
View,
TouchableOpacity,
FlatList,
Alert,
Platform,
PermissionsAndroid,
} from 'react-native';
import Geolocation from 'react-native-geolocation-service';
import BackgroundTimer from 'react-native-background-timer';
const App = () => {
const [isRunning, setIsRunning] = useState(false);
const [locations, setLocations] = useState([]);
const [distance, setDistance] = useState(0);
const [time, setTime] = useState(0);
const [pace, setPace] = useState('0:00');
const locationWatchId = useRef(null);
const timerRef = useRef(null);
const lastLocationRef = useRef(null);
useEffect(() => {
return () => {
stopLocationTracking();
stopTimer();
};
}, []);
useEffect(() => {
if (time > 0 && distance > 0) {
// 计算配速 (分钟/公里)
const paceMinutes = (time / 60) / (distance / 1000);
const paceMin = Math.floor(paceMinutes);
const paceSec = Math.floor((paceMinutes - paceMin) * 60);
setPace(`${paceMin}:${paceSec < 10 ? '0' + paceSec : paceSec}`);
}
}, [time, distance]);
const requestLocationPermission = async () => {
if (Platform.OS === 'ios') {
const granted = await Geolocation.requestAuthorization('always');
return granted === 'granted';
} else {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: '需要位置权限',
message: '跑步追踪App需要访问您的位置信息',
buttonNeutral: '稍后询问',
buttonNegative: '取消',
buttonPositive: '确定',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
}
};
const calculateDistance = (lat1, lon1, lat2, lon2) => {
// 使用Haversine公式计算两点之间的距离
const R = 6371000; // 地球半径,单位米
const dLat = deg2rad(lat2 - lat1);
const dLon = deg2rad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // 距离,单位米
};
const deg2rad = (deg) => {
return deg * (Math.PI / 180);
};
const startLocationTracking = async () => {
const hasPermission = await requestLocationPermission();
if (!hasPermission) {
Alert.alert('权限错误', '无法获取位置权限,请在设置中允许此应用获取位置信息。');
return false;
}
locationWatchId.current = Geolocation.watchPosition(
(position) => {
const { latitude, longitude } = position.coords;
const newLocation = { latitude, longitude, timestamp: position.timestamp };
setLocations(prevLocations => [...prevLocations, newLocation]);
// 计算累计距离
if (lastLocationRef.current) {
const newDistance = calculateDistance(
lastLocationRef.current.latitude,
lastLocationRef.current.longitude,
latitude,
longitude
);
if (newDistance > 1) { // 忽略微小移动,减少误差
setDistance(prevDistance => prevDistance + newDistance);
}
}
lastLocationRef.current = newLocation;
},
(error) => {
console.log('位置获取错误', error);
},
{
enableHighAccuracy: true,
distanceFilter: 5, // 最小距离变化(米),超过此值才会更新位置
interval: 2000, // 位置更新间隔(毫秒)
fastestInterval: 1000, // 最快更新间隔(仅Android)
forceRequestLocation: true,
showLocationDialog: true,
}
);
return true;
};
const stopLocationTracking = () => {
if (locationWatchId.current !== null) {
Geolocation.clearWatch(locationWatchId.current);
locationWatchId.current = null;
}
};
const startTimer = () => {
timerRef.current = BackgroundTimer.setInterval(() => {
setTime(prevTime => prevTime + 1);
}, 1000);
};
const stopTimer = () => {
if (timerRef.current !== null) {
BackgroundTimer.clearInterval(timerRef.current);
timerRef.current = null;
}
};
const formatTime = (seconds) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
return [
hours > 0 ? hours : null,
hours > 0 ? (minutes < 10 ? '0' + minutes : minutes) : minutes,
secs < 10 ? '0' + secs : secs
].filter(Boolean).join(':');
};
const handleToggleRunning = async () => {
if (!isRunning) {
// 开始跑步
const hasPermission = await startLocationTracking();
if (hasPermission) {
setIsRunning(true);
setLocations([]);
setDistance(0);
setTime(0);
setPace('0:00');
lastLocationRef.current = null;
startTimer();
}
} else {
// 结束跑步
stopLocationTracking();
stopTimer();
setIsRunning(false);
// 显示总结信息
Alert.alert(
'跑步结束',
`总距离: ${(distance / 1000).toFixed(2)} 公里\n总时长: ${formatTime(time)}\n平均配速: ${pace}/公里`,
[{ text: '确定', onPress: () => console.log('确认跑步结束') }]
);
// 清零数据
setLocations([]);
setDistance(0);
setTime(0);
setPace('0:00');
lastLocationRef.current = null;
}
};
const renderLocationItem = ({ item, index }) => (
<View style={styles.locationItem}>
<Text style={styles.locationText}>
#{index + 1}: 纬度 {item.latitude.toFixed(6)}, 经度 {item.longitude.toFixed(6)}
</Text>
</View>
);
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>跑步追踪</Text>
</View>
<View style={styles.statsContainer}>
<View style={styles.statBox}>
<Text style={styles.statValue}>{(distance / 1000).toFixed(2)}</Text>
<Text style={styles.statLabel}>距离(公里)</Text>
</View>
<View style={styles.statBox}>
<Text style={styles.statValue}>{formatTime(time)}</Text>
<Text style={styles.statLabel}>时长</Text>
</View>
<View style={styles.statBox}>
<Text style={styles.statValue}>{pace}</Text>
<Text style={styles.statLabel}>配速(分/公里)</Text>
</View>
</View>
<View style={styles.listContainer}>
<Text style={styles.sectionTitle}>位置记录</Text>
<FlatList
data={locations}
renderItem={renderLocationItem}
keyExtractor={(item, index) => index.toString()}
style={styles.list}
contentContainerStyle={styles.listContent}
/>
</View>
<TouchableOpacity
style={[styles.button, isRunning ? styles.stopButton : styles.startButton]}
onPress={handleToggleRunning}
>
<Text style={styles.buttonText}>{isRunning ? '结束跑步' : '开始跑步'}</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f8f9fa',
},
header: {
padding: 16,
backgroundColor: '#4CAF50',
alignItems: 'center',
},
title: {
fontSize: 22,
fontWeight: 'bold',
color: 'white',
},
statsContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
marginVertical: 16,
paddingHorizontal: 8,
},
statBox: {
flex: 1,
alignItems: 'center',
padding: 10,
backgroundColor: 'white',
borderRadius: 8,
margin: 4,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.2,
shadowRadius: 1.5,
elevation: 2,
},
statValue: {
fontSize: 24,
fontWeight: 'bold',
color: '#333',
},
statLabel: {
fontSize: 14,
color: '#666',
marginTop: 4,
},
listContainer: {
flex: 1,
padding: 16,
},
sectionTitle: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 8,
color: '#333',
},
list: {
flex: 1,
backgroundColor: 'white',
borderRadius: 8,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.2,
shadowRadius: 1.5,
elevation: 2,
},
listContent: {
padding: 8,
},
locationItem: {
paddingVertical: 8,
paddingHorizontal: 12,
borderBottomWidth: 1,
borderBottomColor: '#f0f0f0',
},
locationText: {
fontSize: 14,
color: '#333',
},
button: {
margin: 16,
padding: 16,
borderRadius: 8,
alignItems: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
startButton: {
backgroundColor: '#4CAF50',
},
stopButton: {
backgroundColor: '#F44336',
},
buttonText: {
fontSize: 18,
fontWeight: 'bold',
color: 'white',
},
});
export default App;