单字城市名称(例如“加利福尼亚”)会显示结果,但双字“纽约”则不会显示结果

问题描述 投票:0回答:1

这是一个基于 PHP 、 JS 的网页,代表一个天气网站。但是,当我输入任何包含一个单词的任何字符串时,无论它是否是有效的城市名称,它都会提供结果。但是当我在表单中输入任何双字字符串时,它什么也没有显示。但如果我在 api 链接 url 中手动输入城市名称(例如纽约),它会准确显示所有 Jason 数据。

以下是我的代码:

<?php
$status = "";
$msg = "";
$city = "";
if (isset($_POST['submit'])) {
   $city = $_POST['city'];
   $url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=92b2d5275d8ce6c94cd0a72ffc7bd208";
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   $result = curl_exec($ch);
   curl_close($ch);
   $result = json_decode($result, true);
       if ($result['cod'] == 200) {
      $status = "yes";
   } else {
      $msg = $result['message'];
   }

}
?>

<html lang="en" class=" -webkit-">

<head>
    <meta charset="UTF-8">
    <title>Weather</title>
    <style>
    @import url(https://fonts.googleapis.com/css?family=Poiret+One);
    @import url(https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.9/css/weather-icons.min.css);

    body {
        background-image: url("weather.png");
        background-size: cover;
        background-repeat: no-repeat;
        font-family: Poiret One;
        background-blend-mode: screen;
    }

    .widget {
        position: absolute;
        top: 50%;
        left: 50%;
        display: flex;
        height: 300px;
        width: 600px;
        transform: translate(-50%, -50%);
        flex-wrap: wrap;
        cursor: pointer;
        border-radius: 20px;
        box-shadow: 0 27px 55px 0 rgba(0, 0, 0, 0.3), 0 17px 17px 0 rgba(0, 0, 0, 0.15);
    }

    .widget .weatherIcon {
        flex: 1 100%;
        height: 60%;
        border-top-left-radius: 20px;
        border-top-right-radius: 20px;
        background: #FAFAFA;
        font-family: weathericons;
        display: flex;
        align-items: center;
        justify-content: space-around;
        font-size: 100px;
    }

    .widget .weatherIcon i {
        padding-top: 30px;
    }

    .widget .weatherInfo {
        flex: 0 0 70%;
        height: 40%;
        background: darkslategray;
        border-bottom-left-radius: 20px;
        display: flex;
        align-items: center;
        color: white;
    }

    .widget .weatherInfo .temperature {
        flex: 0 0 40%;
        width: 100%;
        font-size: 65px;
        display: flex;
        justify-content: space-around;
    }

    .widget .weatherInfo .description {
        flex: 0 60%;
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
        justify-content: center;
        margin-left: -15px;
    }

    .widget .weatherInfo .description .weatherCondition {
        text-transform: uppercase;
        font-size: 35px;
        font-weight: 100;
    }

    .widget .weatherInfo .description .place {
        font-size: 15px;
    }

    .widget .date {
        flex: 0 0 30%;
        height: 40%;
        background: #70C1B3;
        border-bottom-right-radius: 20px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        color: white;
        font-size: 30px;
        font-weight: 800;
    }

    p {
        position: fixed;
        bottom: 0%;
        right: 2%;
    }

    p a {
        text-decoration: none;
        color: #E4D6A7;
        font-size: 10px;
    }

    .form {
        position: absolute;
        top: 42%;
        left: 50%;
        display: flex;
        justify-content: center;
        align-items: start;
        height: 300px;
        width: 600px;
        transform: translate(-50%, -50%);
    }

    .text {
        width: 65%;
        padding: 10px;
        border-radius: 15px;
        border: 0px;
        -webkit-box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
    }


    .conmain {
        margin-right: 45px;
    }

    button {
        padding: 9px;
        width: 30%;
        border: unset;
        border-radius: 15px;
        color: #212121;
        z-index: 1;
        background: #e8e8e8;
        position: relative;
        font-weight: 1000;
        font-size: 17px;
        -webkit-box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        transition: all 250ms;
        overflow: hidden;
    }

    button::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        width: 0;
        border-radius: 15px;
        background-color: darkslategray;
        z-index: -1;
        -webkit-box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        transition: all 250ms
    }

    button:hover {
        color: #e8e8e8;
    }

    button:hover::before {
        width: 100%;
    }

    #getLocation {
        width: 40%;
    }
    </style>
</head>

<body>
    <div class="form">
        <p><?php
         var_dump($ch)
         ?></p><br>
        <p><?php
         var_dump($result)
         ?></p><br>

        <p><?php var_dump($status)?></p>
        <form style="width:100%;" method="post">
            <input type="text" class="text" placeholder="Enter country or city name" name="city"
                value="<?php echo $city ?>" />
            <button type="submit" value="Submit" class="button" name="submit">submit</button>
            <?php echo $msg ?>
        </form>
        <button id="getLocation">My Location</button>

    </div>

    <?php if ($status == "yes") { ?>
    <article class="widget">
        <div class="weatherIcon">
            <img src="http://openweathermap.org/img/wn/<?php echo $result['weather'][0]['icon'] ?>@4x.png" />
        </div>
        <div class="weatherInfo">
            <div class="temperature">
                <span><?php echo round($result['main']['temp'] - 273.15) ?>°</span>
            </div>
            <div class="description conmain">
                <div class="weatherCondition"><?php echo $result['weather'][0]['main'] ?></div>
                <div class="place"><?php echo $result['name'] ?></div>
            </div>
            <div class="description">
                <div class="weatherCondition">Wind</div>
                <div class="place"><?php echo $result['wind']['speed'] ?> M/H</div>
            </div>
        </div>
        <div class="date">
            <?php echo date('d M', $result['dt']) ?>

        </div>
    </article>
    <?php } ?>

    <script>
    const getLocationButton = document.getElementById("getLocation");
    getLocationButton.addEventListener("click", () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
                const latitude = position.coords.latitude;
                const longitude = position.coords.longitude;

                // Use the latitude and longitude to fetch the location data
                fetchLocationData(latitude, longitude);
            });
        } else {
            alert("Geolocation is not supported by your browser.");
        }
    });

    function fetchLocationData(latitude, longitude) {
        const locationUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`;
        fetch(locationUrl)
            .then((response) => response.json())
            .then((data) => {
                const city = data.address.city || data.address.town || data.address.village;
                if (city) {
                    document.querySelector('input[name="city"]').value = city;
                    // Auto-submit the form by simulating a click on the submit button
                    document.querySelector('[name="submit"]').click();
                }
            })
            .catch((error) => {
                console.error("Error fetching location data:", error);
            });
    }
    </script>
</body>

</html>

无论我在表单中输入多少单词,我都希望得到结果。非常感谢并帮助谢谢。

javascript php api openweathermap weather
1个回答
0
投票

您在天气网站代码中遇到的问题与输入双字城市名称时 API URL 的构建方式有关。问题是您没有在 URL 中正确编码城市名称,这可能会导致城市名称中出现空格问题,例如“纽约”。

为了确保您的代码正确处理带有空格和多个单词的城市名称,您应该使用 PHP 中的“urlencode”函数对城市名称进行编码。这将确保空格和特殊字符在 URL 中正确表示。

这是代码的修改后的 PHP 部分,其中包含城市名称的 URL 编码:

$status = "";
$msg = "";
$city = "";

if (isset($_POST['submit'])) {
    $city = $_POST['city'];
    $encodedCity = urlencode($city); // Encode the city name
    $url = "https://api.openweathermap.org/data/2.5/weather?q=$encodedCity&appid=92b2d5275d8ce6c94cd0a72ffc7bd208";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($result, true);

    if ($result['cod'] == 200) {
        $status = "yes";
    } else {
        $msg = $result['message'];
    }
}

通过此更改,您的代码将在构建 URL 时正确编码城市名称,并且它应该适用于带有空格或特殊字符的城市名称。

现在,您的代码应该可以毫无问题地处理单字和双字城市名称。

© www.soinside.com 2019 - 2024. All rights reserved.