0
点赞
收藏
分享

微信扫一扫

示例 22: 基于地理位置的天气信息

惠特曼 2024-10-11 阅读 14

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather by Location</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            background-color: #f0f2f5;
        }
        .container {
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            text-align: center;
        }
        button {
            padding: 10px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            font-size: 1em;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .weather-info {
            margin-top: 20px;
        }
        .weather-info h2 {
            margin: 0;
        }
        .weather-info p {
            margin: 5px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Weather by Your Location</h1>
        <button onclick="getLocation()">Get Weather</button>
        <div id="weatherInfo" class="weather-info"></div>
    </div>
    <script>
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showWeather, showError);
            } else {
                document.getElementById('weatherInfo').innerHTML = 'Geolocation is not supported by this browser.';
            }
        }

        function showWeather(position) {
            const lat = position.coords.latitude;
            const lon = position.coords.longitude;
            const apiKey = 'YOUR_API_KEY';
            fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}`)
            .then(response => response.json())
            .then(data => {
                const temp = (data.main.temp - 273.15).toFixed(2); // Convert Kelvin to Celsius
                document.getElementById('weatherInfo').innerHTML = `
                    <h2>Weather Information</h2>
                    <p>Location: ${data.name}</p>
                    <p>Temperature: ${temp} °C</p>
                    <p>Weather: ${data.weather[0].description}</p>
                `;
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        function showError(error) {
            let errorMessage = '';
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    errorMessage = "User denied the request for Geolocation.";
                    break;
                case error.POSITION_UNAVAILABLE:
                    errorMessage = "Location information is unavailable.";
                    break;
                case error.TIMEOUT:
                    errorMessage = "The request to get user location timed out.";
                    break;
                case error.UNKNOWN_ERROR:
                    errorMessage = "An unknown error occurred.";
                    break;
            }
            document.getElementById('weatherInfo').innerHTML = errorMessage;
        }
    </script>
</body>
</html>

举报

相关推荐

0 条评论