Build a weather tracking application in the Cloud, part 2nd

Source: Internet
Author: User
Tags php mongodb blank page
In part 1th, I described how to create a basic PHP application and use an online service to retrieve and store the latitude and longitude coordinates of a world city.

Now let's add the new Insights for Weather service from IBM and start using the city information from part 1th to track the weather for your selected 5 world cities. You'll also learn how to host your final application on IBM Bluemix.

Running the sample application

Get code for the sample application

Watch Vikram Progressive Demo code


Prerequisites for completing your application

See part 1th to learn about the prerequisites and software.

1th step. Initializing a Insights for Weather Service instance

Because each location record in the storage database also contains latitude and longitude for that location, you can now integrate your application with the Insights for Weather service. Initially, this service instance will run in an unbound state, allowing you to develop your application locally and host the service instance itself remotely on Bluemix.

READ: Insights for Weather Getting Started

    1. To create a new Insights for Weather instance, you can log in to your Bluemix account and click the Use Services or APIs button in the dashboard. Select Insights for Weather from the list of available services.

    2. Check the description of the service and click CREATE to start it. Make sure the App field is set to Leave Unbound , and that you are using free Plan .

    3. The service instance will now be initialized and you will see a service information page. Make a note of the service name that you need to use it. A navigation bar appears on the left, and click Service Credentials to view the details of the service instance's access.

    4. Copy the contents of the URL field into the Weather_uri key in the application's $APP _root/config.php file. This enables your application to connect to a remote Insights for Weather instance and begin retrieving weather data from it.

2nd step. Show current Weather data

  1. To use the Insights for Weather service, simply request the service URL shown in the previous section and attach the API signature to it. For example, one for API endpoint Https:// The &language=en-us&geocode=51.50853-0.12574 request generates the following response, which shows the current weather in London:
  2. Specifically, the JSON output includes a descriptive phrase for the current weather (such as "Partly cloudy"), as well as current temperature, wind speed, humidity, and other data. To display the same information in your application, you can update the/index route handler function to retrieve a list of stored locations, and then connect to the Insights for Weather service shown above to retrieve the current weather conditions for each location:
    !--? php//index page handlers$app--->get ('/', function () use ($app) {return $app-& Gt;redirect ($app ["Url_generator"]->generate (' Index ');}); $app->get ('/index ', function () use ($app, $db) {//Get list of locations from database//for per location, get CU    Rrent Weather from weather Service $collection = $db->locations;  $locations = Iterator_to_array ($collection->find ()); foreach ($locations as & $location) {$uri = $app->config[' Weather_uri '). '/api/weather/v2/observations/current?units=m&language=en-us&geocode= '.    UrlEncode (sprintf ('%f,%f ', $location [' lat '], $location [' LNG ']);    $json = file_get_contents ($uri);      if ($json = = = FALSE) {throw new Exception ("Could not connect to Weather API.");  } $location [' weather '] = Json_decode ($json, true); } return $app [' Twig ']->render (' Index.twig ', Array (' locations ' = = $locations)}) ->bind (' index '); 
  3. Next, update the Twig template on the $APP _root/views/index.twig to display this information:

    Current Weather

      {% for item in locations%}
    • {{Item.location}}, {{}}
      {{}}°c | {{}} Remove
    • {% ENDFOR%}

    ADD Location

  4. This is the appearance of the template. If you prefer to use icons instead of text, the Insights for Weather service provides a complete set of icons and instructions on how to use them.

Note that there is a Delete button next to each location, which links to the/delete route handler and passes the unique MongoDB record identifier for that location to this handler function. The/delete processing function deletes the specified record from the MongoDB database:

  Get ('/delete/{id} ', function ($id) use ($app, $db) {  $collection = $db->locations;  $collection->remove (Array (' _id ' = = new MongoId ($id)));  Return $app->redirect ($app ["Url_generator"]->generate (' index '));}) ->bind (' delete ');

3rd step. Retrieving weather forecasts

  1. Just as you can retrieve the current weather conditions at any location, the Insights for Weather service also allows you to retrieve the weather forecast for that location within 10 days. Update your API request to language=en-us&geocode=51.50853-0.12574, you will receive detailed information about the weather conditions for the day and night, as shown below. Note The Dow and narrative fields in the input, which represent the day of the week and the forecast information fragment for this date, because these are the primary fields used by the application.
  2. to add this functionality to your application, you can create a new handler for the/forecast route, pass it the location identifier in the database, and then insert the coordinates of that value into the API request above. Here is the relevant code:
     "!--? php//handler to display 7-day forecast for selected Location$app---" Get ('/forecast/{id} ', function ($id) use ($app, $db) {//Look up location record in database//Connect and get Forecas  T from Weather service $collection = $db->locations;  $location = (array) $collection->findone (Array (' _id ' = = new MongoId ($id)); $uri = $app->config[' Weather_uri '). '/api/weather/v2/forecast/daily/10day?units=m&language=en-us&geocode= '.  UrlEncode (sprintf ('%f,%f ', $location [' lat '], $location [' LNG ']);  $json = file_get_contents ($uri);    if ($json = = = FALSE) {throw new Exception ("Could not connect to Weather API.");  } $location [' weather '] = Json_decode ($json, true); return $app [' Twig ']->render (' Forecast.twig ', Array (' data ' = $location));}) ->bind (' forecast '); 
  3. You can also add a page template to the new handler and link to it from the main index page. The template can be found in the application's code repository. The following is an example of this tab:

4th step. Deploy your application to IBM Bluemix

Now that the application is complete, you can deploy it to Bluemix.

  1. First, update the application configuration files and modify the database credentials to point to your remote MongoDB database deployment.
  2. Then, create the application manifest file, remembering to use a unique host and application name by attaching an immediate string, such as the first letter of your name.
    ---applications:-name:weather-tracker-[initials]memory:256minstances:1host:weather-tracker-[initials]buildpack : HTTPS://GITHUB.COM/CLOUDFOUNDRY/PHP-BUILDPACK.GITSTACK:CFLINUXFS2
  3. Cloudfoundry PHP buildpack does not include PHP MongoDB extensions by default, so you must configure the Buildpack to enable the extension during deployment. Also, if you want to automatically get Insights for Weather service credentials from Bluemix, you can update the code to use the Bluemix vcap_services variable as follows:
        config[' Weather_uri ' = $services _json["weatherinsights"][0]["credentials" ["url"];}
  4. You now see that you can continue to push the application to Bluemix and then bind the Insights for Weather service to the application.
    Shell> CF API Https://> CF loginshell> CF pushshell> CF Bind-service weather-tracker- [Initials] "Insights for Weather-[id]" shell> CF restage Weather-tracker-[initials]

You can now browse to the host specified in the application manifest to start using the application, such as http://weather-tracker-[initials]. If you see a blank page or other error, you can try debugging your PHP code to find the wrong place.

READ: Debugging PHP errors on IBM Bluemix


The Insights for Weather service makes it easy to add location-specific weather data and forecasts to mobile or WEB applications. Because you can access the service through the REST API, you can integrate it with any programming language. Also, because the service is hosted on Bluemix, it's easy to connect it to your Bluemix-hosted application, just bind the service to your application and reload it.

You can download all the code implemented in this tutorial, along with the PHP buildpack configuration file, from the link above. It is recommended that you get the code, use it, and try to add some new features. I guarantee that you will not cause any damage, and it is certainly helpful to your study. Wish you a pleasant development!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.