首页 > 解决方案 > 如何将一个 HTML 表单输入发送到两个不同的 API 并从中获取结果?

问题描述

我正在尝试制作一个带有地图的 3 天天气预报页面。我正在使用 Openweathermap API 和一些 PHP 来获取预测。我正在使用 Google 的 Maps JavaScript API 来获取我的地图。该页面有一个输入字段。我可以做到,以便提交输入会给我天气预报。我可以做到,这样输入就会给我地图。但我不能让两者同时发生。

这是HTML表单

<form class="example" method="GET" action="index.php" style="margin:auto;max-width:300px">
<h3>Type In a Zipcode</h3>
<br><p>For Example 160-0005</p>

<!--test-->
<input id="address" type="textbox" value="" name="q" required>
<button id= "OK!"  type="submit"><i class="fa fa-search"></i></button>

这是PHP

 date_default_timezone_set($get['timezone']);
 $city = $_GET['q'];
 $string =  "http://api.openweathermap.org/data/2.5/forecast?zip=".$city.",jp&units=metric&cnt=3&appid=[API Key]";

这是JavaScript

<script>
      "use strict";

      function initMap() {
        const map = new google.maps.Map(document.getElementById("map"), {
          zoom: 15,
          center: {
            lat: -34.397,
            lng: 150.644
          }
        });
        const geocoder = new google.maps.Geocoder();
        document.getElementById("OK!").addEventListener("click", () => {
          geocodeAddress(geocoder, map);
        });
      }

      function geocodeAddress(geocoder, resultsMap) {
        const address = document.getElementById("address").value;
        geocoder.geocode(
          {
            address: address
          },
          (results, status) => {
            if (status === "OK") {
              resultsMap.setCenter(results[0].geometry.location);
              new google.maps.Marker({
                map: resultsMap,
                position: results[0].geometry.location
              });
            } else {
              alert(
                "Geocode was not successful for the following reason: " + status
              );
            }
          }
        );
      }
    </script>

在 HTML 表单代码中,如果我将按钮类型更改为“按钮”,JavaScript 就会工作并显示地图。如果我将其更改为“提交”,PHP 将工作并给我预测。不太确定那里发生了什么。如何输入位置信息并同时获取地图和预报?

标签: javascriptphphtmlformsapi

解决方案


在你的javascript中:

   var address = "<?php isset($_GET['q']) ? $_GET['q'] : ''?>";
   
   function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 15,
      center: {
        lat: -34.397,
        lng: 150.644
      }
    });
    const geocoder = new google.maps.Geocoder();

    address !== '' && geocodeAddress(geocoder, map, address);
  }

  // have geocodeAddress accept third param of address
  function geocodeAddress(geocoder, resultsMap, address) {
       ... rest of your code

这都是未经测试的。让我知道它是否适合您(或不适合)


推荐阅读