Know weather information by php and weather api

Hi, You have been waiting a lot. We are back with Google Maps, but we have a good add-on this time. Get weather information at your current location by sharing location from browser or at any other place. This is pretty cool, you can get the weather at any location in the world and it too precise to 1 Hr.

We are going to use google maps API and weather API from https://openweathermap.org/

First we will build a interface to retrieve the current location from the browser and then pan to that location on google maps and alternatively make a search box which can search through location and pan to selected location on google map. Keep in mind our sole aim here is to get the latitude and longitude co-ordinates of the location selected.

1. Creating a Get location from Browser

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
	x.innerHTML = " <br>Location : (" + position.coords.latitude + " , " +  + position.coords.longitude + " )";		
	lat =  position.coords.latitude;
    lon = position.coords.longitude;

    //show location on map
    var loc = new google.maps.LatLng(position.coords.latitude,position.coords.longitude) ;
    var marker = new google.maps.Marker({
        map: map,
        position: loc
      });

    markers.push(marker);
	var bounds = new google.maps.LatLngBounds();
    bounds.extend(loc);
    map.fitBounds(bounds);
    map.setZoom(7);
    showweather();
} 
</script>

It is really easy to understand the above part of code. The function  getLocation() is the real player. It asks the browser to get the current location. And secondly function  showPosition(position)  will display the received latitude and longitude on the google map and a marker for the position. It will also pan to that location.

2. Getting Location from a search box

<script>

var map;
var markers = [];
var lat,lon,appid;
function initialize() {


  map = new google.maps.Map(document.getElementById('map-canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-33.8902, 151.1759),
      new google.maps.LatLng(-33.8474, 151.2631));
  map.fitBounds(defaultBounds);

  // Create the search box and link it to the UI element.
  var input = (document.getElementById('pac-input'));
  
  var searchBox = new google.maps.places.SearchBox((input));

  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.
  google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();

    if (places.length == 0) {
      return;
    }
    for (var i = 0, marker; marker = markers[i]; i++) {
      marker.setMap(null);
    }

    // For each place, get the icon, place name, and location.
    markers = [];
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
      var image = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };

      // Create a marker for each place.
      var marker = new google.maps.Marker({
        map: map,
        icon: image,
        title: place.name,
        position: place.geometry.location
      });

    markers.push(marker);
		var x = document.getElementById("demo");
       x.innerHTML = " <br>Location : " + place.geometry.location ;	
       lat = place.geometry.location.lat();
       lon = place.geometry.location.lng();


      bounds.extend(place.geometry.location);
       map.panTo(place.geometry.location);
    
    }

    map.fitBounds(bounds);
    map.setZoom(7);
    showweather();
   
  });

  // Bias the SearchBox results towards places that are within the bounds of the
  // current map's viewport.
  google.maps.event.addListener(map, 'bounds_changed', function() {
    var bounds = map.getBounds();
    searchBox.setBounds(bounds);
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>

This is just the javascript code for what we aim to do. The html code for the same is given below. Just keep looking.

Understanding the code  :

var input1 = (document.getElementById(‘pac-input1’));

You need to create a input element in your body to place this input field.

<input id=”pac-input1″ class=”control” type=”text” placeholder=”From ->”>

var searchBox1 = new google.maps.places.SearchBox((input1));

This is place where we are creating a search box and below it we are creating a listener which will listen to inputs given by user to the search box. On starting to enter some text into the box, it will search for relevant places and get icon, name and location of the place and then On selecting it, it will create a marker for that place. We are also storing those markers.

So, Now We have the co-ordinates for the location we want weather details for. Let move forward.

We are going to use a weather api. The API is provided by https://openweathermap.org . We are here using the free version and listen to me if are doing some personal and not commercial stuff, free plan is enough for you.

This service provides a restAPI.

GET Request to URI : http://api.openweathermap.org/data/2.5/weather?lat=””&lon=””&appid=””

So we are going to use a ajax call to send a get request to above URI and pass variables lat and lon in get request.

<script type="text/javascript">
	function showweather()
	{	
		$.ajax({
					url: "http://api.openweathermap.org/data/2.5/weather",
					type: 'GET',
					data: {"lat":lat,
				           "lon":lon,
				           "appid":'abd24802c4da9c011e2b2cbb6ec721ec'},
					success: function (result) {
						var data =  JSON.parse(JSON.stringify(result));
						var y = document.getElementById("weather");
						var str = "<h3><strong>Weather at </strong> "+data["name"]+"</h3><br>";
						str += "<img src='http://openweathermap.org/img/w/"+data["weather"][0]["icon"]+".png'></img>";
						str += "<strong>"+data["weather"][0]["main"]+"</strong>  "+data["weather"][0]["description"]+"<br>";
						str += "<table class='table table-striped'>";
						str += "<tr><td><strong>Temperature   </strong>  </td><td>"+(parseInt(data["main"]["temp"])-273.15)+" Celcius</td></tr>";
						str += "<tr><td><strong>Pressure    </strong>  </td><td>"+data["main"]["pressure"]+" hPa</td></tr>";
						str += "<tr><td><strong>Humidity   </strong> </td><td> "+data["main"]["humidity"]+" %</td></tr>";
						str += "<tr><td><strong>Temp_min   </strong> </td><td> "+(parseInt(data["main"]["temp_min"])-273.15)+" Celcius</td></tr>";
						str += "<tr><td><strong>Temp_max   </strong>  </td><td>"+(parseInt(data["main"]["temp_max"])-273.15)+" Celcius</td></tr>";
						str += "<tr><td><strong>Sea level   </strong> </td><td> "+data["main"]["sea_level"]+" hPa</td></tr>";
						str += "<tr><td><strong>Ground level   </strong>  </td><td>"+data["main"]["grnd_level"]+" hPa<br></td></tr>";
						str += "<tr><td><strong>Wind Speed   </strong> </td><td> "+data["wind"]["speed"]+" hPa</td></tr>";
						str += "<tr><td><strong>Wind Degrees   </strong> </td><td> "+data["wind"]["deg"]+" hPa</td></tr></table>";
			
						y.innerHTML = str;
					}
				});
	}
</script>

On Success, we have the parse the json that we received and we are taking contents from that json to put on a display in already created weather element in html. Look below for the json format of the responce.

{
    "coord": {
        "lon": 77.7,
        "lat": 12.98
    },
    "weather": [
        {
            "id": 210,
            "main": "Thunderstorm",
            "description": "light thunderstorm",
            "icon": "11d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 300.91,
        "feels_like": 304.51,
        "temp_min": 299.82,
        "temp_max": 302.04,
        "pressure": 1008,
        "humidity": 74
    },
    "visibility": 6000,
    "wind": {
        "speed": 2.1,
        "deg": 330
    },
    "clouds": {
        "all": 75
    },
    "dt": 1595158497,
    "sys": {
        "type": 1,
        "id": 9205,
        "country": "IN",
        "sunrise": 1595118693,
        "sunset": 1595164744
    },
    "timezone": 19800,
    "id": 1277333,
    "name": "Bengaluru",
    "cod": 200
}

Reference : https://openweathermap.org/current

I think thats it for today. And yes the complete code is here.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
     <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0-rc2/css/bootstrap.css" rel="stylesheet" media="screen">
    <!-- Bootstrap CSS -->
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
    <title>Weather| Webtut+</title>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
     <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      .controls {
        margin-top: 16px;
        border: 1px solid transparent;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        height: 32px;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        /*margin-left: 12px;*/
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 200px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      .pac-container {
        font-family: Roboto;
      }

      #type-selector {
        color: #fff;
        background-color: #4d90fe;
        padding: 5px 11px 0px 11px;
      }

      #type-selector label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
    </style>
<script>

var map;
var markers = [];
var lat,lon,appid;
function initialize() {

  map = new google.maps.Map(document.getElementById('map-canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-33.8902, 151.1759),
      new google.maps.LatLng(-33.8474, 151.2631));
  map.fitBounds(defaultBounds);

  // Create the search box and link it to the UI element.
  var input = (document.getElementById('pac-input'));
  
  var searchBox = new google.maps.places.SearchBox((input));

  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.
  google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();

    if (places.length == 0) {
      return;
    }
    for (var i = 0, marker; marker = markers[i]; i++) {
      marker.setMap(null);
    }

    // For each place, get the icon, place name, and location.
    markers = [];
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
      var image = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };

      // Create a marker for each place.
      var marker = new google.maps.Marker({
        map: map,
        icon: image,
        title: place.name,
        position: place.geometry.location
      });

    markers.push(marker);
		var x = document.getElementById("demo");
       x.innerHTML = " <br>Location : " + place.geometry.location ;	
       lat = place.geometry.location.lat();
       lon = place.geometry.location.lng();

      bounds.extend(place.geometry.location);
       map.panTo(place.geometry.location);
    
    }

    map.fitBounds(bounds);
    map.setZoom(7);
    showweather();
   
  });

  // Bias the SearchBox results towards places that are within the bounds of the
  // current map's viewport.
  google.maps.event.addListener(map, 'bounds_changed', function() {
    var bounds = map.getBounds();
    searchBox.setBounds(bounds);
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>

<h1 class="text-center">Know weather at your location</h1>
<div  class="col-sm-5" id="map-canvas"></div>
<div  class="col-sm-7" >
<button onclick="getLocation()" class="btn btn-info">Get your Location </button>  <strong> OR</strong>
<span>Enter it manually here</span>
<input id="pac-input" class="control" type="text" placeholder="Enter Location">
<button class="btn btn-warning" onclick="showweather()">Get Weather</button>
<p id="demo"></p>
<p id="weather"></p>
</div>
<script type="text/javascript">
	function showweather()
	{	
		$.ajax({
					url: "http://api.openweathermap.org/data/2.5/weather",
					type: 'GET',
					data: {"lat":lat,
				           "lon":lon,
				           "appid":'abd24802c4da9c011e2b2cbb6ec721ec'},
					success: function (result) {
						var data =  JSON.parse(JSON.stringify(result));
						var y = document.getElementById("weather");
						var str = "<h3><strong>Weather at </strong> "+data["name"]+"</h3><br>";
						str += "<img src='http://openweathermap.org/img/w/"+data["weather"][0]["icon"]+".png'></img>";
						str += "<strong>"+data["weather"][0]["main"]+"</strong>  "+data["weather"][0]["description"]+"<br>";
						str += "<table class='table table-striped'>";
						str += "<tr><td><strong>Temperature   </strong>  </td><td>"+(parseInt(data["main"]["temp"])-273.15)+" Celcius</td></tr>";
						str += "<tr><td><strong>Pressure    </strong>  </td><td>"+data["main"]["pressure"]+" hPa</td></tr>";
						str += "<tr><td><strong>Humidity   </strong> </td><td> "+data["main"]["humidity"]+" %</td></tr>";
						str += "<tr><td><strong>Temp_min   </strong> </td><td> "+(parseInt(data["main"]["temp_min"])-273.15)+" Celcius</td></tr>";
						str += "<tr><td><strong>Temp_max   </strong>  </td><td>"+(parseInt(data["main"]["temp_max"])-273.15)+" Celcius</td></tr>";
						str += "<tr><td><strong>Sea level   </strong> </td><td> "+data["main"]["sea_level"]+" hPa</td></tr>";
						str += "<tr><td><strong>Ground level   </strong>  </td><td>"+data["main"]["grnd_level"]+" hPa<br></td></tr>";
						str += "<tr><td><strong>Wind Speed   </strong> </td><td> "+data["wind"]["speed"]+" hPa</td></tr>";
						str += "<tr><td><strong>Wind Degrees   </strong> </td><td> "+data["wind"]["deg"]+" hPa</td></tr></table>";
			
						y.innerHTML = str;
					}
				});
	}
</script>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
	x.innerHTML = " <br>Location : (" + position.coords.latitude + " , " +  + position.coords.longitude + " )";		
	lat =  position.coords.latitude;
    lon = position.coords.longitude;

    //show location on map
    var loc = new google.maps.LatLng(position.coords.latitude,position.coords.longitude) ;
    var marker = new google.maps.Marker({
        map: map,
        position: loc
      });

    markers.push(marker);
	var bounds = new google.maps.LatLngBounds();
    bounds.extend(loc);
    map.fitBounds(bounds);
    map.setZoom(7);
    showweather();
} 
</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *