Build a weather tracking application in the cloud, Part 1-php Tutorial

Source: Internet
Author: User
Tags php mongodb
Building a weather tracking application in the cloud, Part 1 in Part 2 describes how to create a basic PHP application and use an online service to retrieve and store the latitude and longitude coordinates of world cities.

Now let's add the new Insights for Weather service from IBM and start to use city information from Part 1 to track the Weather in the five world cities you selected. You will also learn how to host your final application on IBM Bluemix.

Run the sample application

Obtain the code of the sample application

Watch Vikram step-by-step demonstration of code copywriting

Prerequisites for completing your application

See section 1st for the required knowledge and software.

Step 2. initialize an Insights for Weather Service instance

Because each location record in the storage database also contains the latitude and longitude of the location, you can now integrate your application with the Insights for Weather service. Initially, this service instance runs in an unbound state; this enables you to develop applications locally and remotely host the service instance on Bluemix.

Read: Getting started with Insights for Weather

  1. To create a new Insights for Weather instance, log on to your Bluemix account and clickUse Services or APIsButton. SelectInsights for Weather.

  2. Check the description of the service and clickCREATETo start it. Make sure that the App field is setLeave unboundAnd you are usingFree Plan.

  3. The service instance will be initialized now, and you will see a service information page. Write down the service name. you need to use it. A navigation bar is displayed on the left. clickService CredentialsView the access details of the service instance.

  4. Copy the url field content to the weather_uri key in the $ APP_ROOT/config. php file of the application. This enables your application to connect to a remote Insights for Weather instance and start retrieving Weather data from it.
Step 2. display current weather data
  1. To use the Insights for Weather service, you only need to request the service URL displayed in the previous section and add the API signature to it. For example, an HTTP: // USERNAME: PASSWORD@twcservice.mybluemix.net/API/weather/v2/observations/current? Units = m & language = en-US & geocode = 51.50853-0.12574 requests will generate the following response, which shows the current weather in London:
  2. Specifically, JSON output includes descriptive phrases of the current weather (such as "Partly cloudy"), as well as the current temperature, wind speed, humidity, and other data. To display the same information in your application, you can update the/index routing function to retrieve the list of storage locations; connect to the Insights for Weather service shown above to retrieve the current Weather conditions for each location:
       get('/', function () use ($app) {  return $app->redirect($app["url_generator"]->generate('index'));});$app->get('/index', function () use ($app, $db) {  // get list of locations from database  // for each location, get current 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 $ APP_ROOT/views/index. Twig to display this information:

    Current Weather

      {% for item in locations %}
    • {{ item.location }}, {{ item.country }}
      {{ item.weather.observation.metric.temp }}° C | {{ item.weather.observation.phrase_22char }} 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 that links to the/delete routing handler and passes the unique MongoDB record identifier of the location to this handler. The/delete 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');
Step 2. search for 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 Weather forecasts for the location within 10 days. Update your API request to https: // USERNAME: PASSWORD@twcservice.mybluemix.net/api/weather/v2/forecast/daily/10day? Units = m & language = en-US & geocode = 51.50853-0.12574. you will receive detailed information about weather conditions during the day and night, as shown below. Note that the dow and narrative fields in the input indicate the day of the week and the forecast information fragment of the day, because these are the main fields used by the application.
  2. To add this function to your application, you can create a new handler for the/forecast route and pass it the location identifier in the database, then insert the coordinates of the value into the above API request. The following code is used:
       get('/forecast/{id}', function ($id) use ($app, $db) {  // look up location record in database  // connect and get forecast 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 for the new handler and link it from the primary index page. You can find this template in the application code repository. The following is an example of this tab:
Step 2. deploy your application to IBM Bluemix

Now that the application has been completed, you can deploy it to Bluemix.

  1. First, update the application configuration file and modify the database creden。 so that they point to your remote MongoDB database deployment.
  2. Create an application list file and remember to use a unique host and application name by appending a 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 the PHP MongoDB extension by default. Therefore, you must configure this buildpack to enable this extension during deployment. In addition, if you want to automatically obtain the Insights for Weather service credential from Bluemix, you can update this code to use the Bluemix VCAP_SERVICES variable, as shown below:
       config['weather_uri'] = $services_json["weatherinsights"][0]["credentials"]["url"];}
  4. Now you can continue to push the application to Bluemix, and then bind the Insights for Weather service to the application.
    shell> cf api https://api.ng.bluemix.netshell> 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 list to start using the application, such as http: // weather-tracker-[initials] .mybluemix.net. If you see a blank page or other errors, you can try to debug your PHP code to find the error.

Read: Debugging PHP errors on IBM Bluemix

Conclusion

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 this service through the rest api, you can integrate it with any programming language. In addition, because the service is hosted on Bluemix, it is easy to connect it to your Bluemix-hosted application, simply bind the service to your application and reload it.

You can download all the code implemented in this tutorial and the configuration file of PHP buildpack from the above link. We recommend that you get the code, use it, and try to add some new features. I promise you will not cause any damage, and it will certainly help your learning. 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: info-contact@alibabacloud.com 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.