|
| 1 | +import React, { useState } from 'react'; |
| 2 | + |
| 3 | +const MyFirstHTML5WebStorageEx4 = () => { |
| 4 | + const [location, setLocation] = useState(null); |
| 5 | + const [error, setError] = useState(null); |
| 6 | + const [watchId, setWatchId] = useState(null); |
| 7 | + |
| 8 | + const startTracking = () => { |
| 9 | + if (navigator.geolocation) { |
| 10 | + const id = navigator.geolocation.watchPosition( |
| 11 | + (position) => showPosition(position), |
| 12 | + (error) => showError(error) |
| 13 | + ); |
| 14 | + setWatchId(id); |
| 15 | + } else { |
| 16 | + setError('Geolocation is not supported by this browser.'); |
| 17 | + } |
| 18 | + }; |
| 19 | + |
| 20 | + const stopTracking = () => { |
| 21 | + if (watchId) { |
| 22 | + navigator.geolocation.clearWatch(watchId); |
| 23 | + setWatchId(null); |
| 24 | + setLocation(null); |
| 25 | + setError(null); |
| 26 | + } |
| 27 | + }; |
| 28 | + |
| 29 | + const showPosition = (position) => { |
| 30 | + const { latitude, longitude } = position.coords; |
| 31 | + setLocation(`Latitude: ${latitude}, Longitude: ${longitude}`); |
| 32 | + }; |
| 33 | + |
| 34 | + const showError = (error) => { |
| 35 | + setError(`Error: ${error.message}`); |
| 36 | + }; |
| 37 | + |
| 38 | + return ( |
| 39 | + <div> |
| 40 | + <h1>My First Geolocation Example</h1> |
| 41 | + <button onClick={startTracking}>Start Tracking</button> |
| 42 | + <button onClick={stopTracking}>Stop Tracking</button> |
| 43 | + <p>{location ? location : error}</p> |
| 44 | + </div> |
| 45 | + ); |
| 46 | +}; |
| 47 | + |
| 48 | +export default MyFirstHTML5WebStorageEx4; |
0 commit comments