0

I am trying to make a page that gives a 3 day weather forecast with a map. I am using the Openweathermap API and some PHP to get the forecast. I am using Google's Maps JavaScript API to get my map. The page has a single input field. I can make it so that submitting input will give me the weather forecast. I can make it so that input will give me the map. But I cannot get both to happen at the same time.

Here is the HTML form

<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>

Here is the 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]";

here is the 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>

In the HTML form code, if I change the button type to "button", the JavaScript works and displays the map. If I change it to type "submit", the PHP works and gives me the forecast. Not really sure what is going on there. What can I do to enter location information and get the map and the forecast at the same time?

2 Answers2

0

in you 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

this is all untested. let me know if its works for your (or doesn't)

Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
  • Thanks a lot for helping. I like this idea. I was adding your code and testing. Everything was working fine. But when I added a third parameter (address) to geocodeAddress() it broke. The map would no longer appear on the page. – at_ease_jonathan Sep 21 '20 at 09:00
  • broke like how? can check the console maybe to see if there are any related errors – Sumit Wadhwa Sep 21 '20 at 09:21
  • The console gave me "Uncaught SyntaxError: Identifier 'address' has already been declared" and it pointed to the following line: const address = document.getElementById("address").value; – at_ease_jonathan Sep 21 '20 at 12:34
  • you need to remove `const address = document.getElementById("address").value;` because you're getting address in the param – Sumit Wadhwa Sep 21 '20 at 12:42
  • That got rid of the error. The map is back but it's location does not update when I put in an address. Weather updates fine. Anyway, I really appreciate your help. I'll keep working on it. If you see the whole file it might give you a better idea. Let me know if you are interested. – at_ease_jonathan Sep 21 '20 at 13:11
0

Your form isn't submitted when using the button element because you're not specifying the form attribute : HTML form Attribute

Also, you will likely have to use a javascript http client to send the form instead of just submitting it. The most known and documented one would be Ajax from jquery. jQuery - AJAX get() and post() Methods This will allow you to send data to your back-end(php) transparently without refreshing the page on each form (post or get request) you make.

Good luck with your project :)

EDIT : CODE edited with form attribute.

<form id="form1" 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>

<!--When using a button, potentially out of the form block-->
<!--You should fill the "form" attribute based on the form's ID-->
<button id= "OK!"  type="submit" form=form1"><i class="fa fa-search"></i></button></form>

Also I don't know if it's only from your sample code but there is a missing </form> tag.

CrazyYoshi
  • 1,003
  • 1
  • 8
  • 19
  • Thanks for checking it out. I will look into using AJAX. I am sorry, but I could not quite follow your first comment. Would you mind showing me in the code? Do you mean I left out out at the end? – at_ease_jonathan Sep 23 '20 at 14:33
  • I edited my answer to demonstrate what I meant. As for jQuery and Ajax, it should be pretty straight forward to implement. – CrazyYoshi Sep 24 '20 at 14:15
  • Thanks for clarifying. I added the form attribute in the inside the button so that it matched id of the form. It did not seem to change any of the functionality when running the program though. Should I have noticed a change? – at_ease_jonathan Sep 25 '20 at 02:41