javascript - 如何将一个 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 将工作并给我预测。不太确定那里发生了什么。如何输入位置信息并同时获取地图和预报?
解决方案
在你的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
这都是未经测试的。让我知道它是否适合您(或不适合)
推荐阅读
- android - 显示一周内正在进行的活动(例如课程、睾丸)的时间表
- php - 提交表单后回显 div 类
- c# - 查找并替换段落中的字符串
- mysql - 如何从 varchar 列 mysql 中过滤数据
- dart - 如何在不传递传递参数的情况下递归调用方法?
- python - 找出随机森林模型中有多少袋外记录
- windows-subsystem-for-linux - .conf 更改对 WSL 中的重新启动没有影响?
- python - Pytrends - 随时间变化的兴趣 - 没有数据时返回无列
- alpine.js - $dispatch 选择更改事件以更新按钮焦点
- javascript - 将文本绘制到行(x1,y1,x2,y2)时旋转和转换值(使用 p5.js,处理 ... atan2)