Get World Countries and Cities Weather with their Geolocations (API -JSON).


Let’s have a bit of fun and let’s build a Visualforce page that is going to call an API via HTTP and to get in return the latitude and longitude of any country plus their cities. We are going to receive their weather conditions as well. We are going to add an option to get the country and/or a city from that country to narrow the response. All this information will be retrieved in JSON and will be displayed in our Visualforce page. We are going to use “Continuation Class” for this example

Let’s take a look at what it is that we need in order to successfully accomplish this tutorial.

1. We need an API key from https://www.wunderground.com/
How do you get an API key? You need to register and apply for a developer API key, it is easy and a fast process.
After registering and requesting an API key you will receive an email with your API key that we will be needing to call their API through HTPP.

2. Set up the Remote Site
3. Eclipse, MavensMate or any developer environment that you use for coding apex.
4. A SFDC org
5. Coffee … plenty of coffee

First, navigate to wunderground.com and get your API key. On wunderground’s site, you can find plenty of documentation on how to use their API but we only need to concentrate on one Service URL, this one:

'http://api.wunderground.com/api/<your API KEY HERE>/geolookup/conditions/forecast/q/'

Before we look into that we need to prepare our org to allow us to execute callouts to wunderground. For this, we need to set up a Remote Site. Just go to Setup –> Administer –> Security Controls –> Remote Site Settings.

Now, all we need to do is to click on New Remote Site.
On the remote site name enter whatever feels the best for you, the other options need to be equals to those in the screenshot bellow:

Click Save and we are good to go.

If you want to know more about Remote Site Settings check this page. Also consider the “Named Credentials” as an option for you callouts. Ok, now we have registered our site in our SFDC org will allow us to make callouts to that external site!


Right now we should have our wunderground API key and the Remote Site should be registered and active.

Our flow should follow these steps that you can see on this screenshot taken from SFDC documentation:

Execution Flow of an Asynchronous Callout


Now that we know the flow it is time to deploy our apex class.

/**************************************************************
* @Author   : Carlos Naranjo 
* @Website  : http://ccloudonline.nl - http://ccloudonline.com
*
***************************************************************/

public with sharing class WeatherService {
    
    
    public String requestLabel;
    public String result {get;set;}
    public String countryISO {get;set;}
    public String city{get;set;}

    
    private static final String LONG_RUNNING_SERVICE_URL = 
        'http://api.wunderground.com/api/<YOUR API KEY HERE>/geolookup/conditions/forecast/q/';
        

        

        public WeatherService()
        {
            countryISO ='Spain';
            city='Sevilla'; 
        }
   
   // Action method
    public Object startRequest() {
      // Create continuation with a timeout
      Continuation con = new Continuation(60);
      // Set callback method
      con.continuationMethod='processResponse';
      
      // Create callout request
      HttpRequest req = new HttpRequest();
      req.setMethod('GET');
      req.setEndpoint(LONG_RUNNING_SERVICE_URL+countryISO+'/'+city+'.json');
      
      // Add callout request to continuation
      this.requestLabel = con.addHttpRequest(req);
      
      // Return the continuation
      return con;  
    }
    
    // Callback method 
    public Object processResponse() {   
      // Get the response by using the unique label
      HttpResponse response = Continuation.getResponse(this.requestLabel);
      // Set the result variable that is displayed on the Visualforce page
      this.result = response.getBody();
      
      // Return null to re-render the original Visualforce page
      return null;
    }
}

On the line where you can see the SERVICE URL you need to insert your wunderground API key:

From this:

'http://api.wunderground.com/api/<YOUR API KEY HERE>/geolookup/conditions/forecast/q/';

To something similar to this, the only change is that we have inserted the API key we received from wunderground :

'http://api.wunderground.com/api/68ba9fl743d42102/geolookup/conditions/forecast/q/';

When that change is done you can save your class because it is ready.

The last step is to build our Visualforce page with a button that will trigger the call out. It is going to be something really simple and the response will be in JSON.

This is the Visualforce page:


<apex:page controller="WeatherService" tabStyle="Account" showHeader="true" sidebar="false" docType="html-5.0">
 <apex:form>
 	<apex:pageBlock title="Your Geolocation and Weather Service">
 		Country:
 		<apex:input label="Country" value="{!countryISO}"/>
 		City:
 		<apex:input label="City" value="{!city}"/>
 		<apex:commandButton action="{!startRequest}" value="Geolocation and Weather Service" reRender="weatherPanel"/>

 	</apex:pageBlock>

 	    <apex:pageBlock title="Weather Service Response" id="weatherPanel">
 	    <pre>{!result}</pre>
 	    </apex:pageBlock>
 </apex:form>
	
</apex:page>


Now we are ready to test our page. You can use the country ISO for the countries or the full name.
It is possible to search only for the country and leave the city field empty. This is a simple page and there is not error handling or any other fancy UI behavior, but I hope that it helps you to understand a bit better how to get JSON response on a Visualforce page.

If you click the “Geolocation and Wheater Service” you should receive a JSON response on the body of the page, something similar to this:

On this screenshot, you can only see the very first lines but you will find that there is a lot of information coming from the JSON response. This is and easy way to also demonstrate the “Continuation Class”, so I hope that you enjoyed your coffee and this tutorial.
Questions? issues? leave a comment bellow and I will do my best to answer ASAP.

Jump to part 2 of this example to display your parsed JSON response in a proper way on a Visualfroce page.

Leave a Reply

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