【发布时间】:2020-09-21 07:07:11
【问题描述】:
我正在尝试制作一个带有地图的 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 php html forms api