Polymer paper elements (material design)

paper-button is a button containing text or an image. When the user touches the button, a ripple effect emanates from the point of contact.

A paper-button may be flat or raised. A raised button behaves like a piece of paper resting on another sheet, and lifts up upon press. Flat buttons do not raise up. Add the raisedButton attribute to make a raised button.


<paper-button label="flat button"></paper-button>
<paper-button label="raised button" raisedButton></paper-button>

A button should be styled with a background color, text color, ripple color and hover color.

To style the background, text and hover color, apply the background and color CSS properties to the button. To style the ripple color, apply the color CSS property to the #ripple element in the button’s shadow root:

/* Style #my-button blue with white text and darker blue ink. */
#my-button {
    background: #4285f4;
    color: #fff;

#my-button:hover {
    background: #2a56c6;

#my-button::shadow #ripple {
    color: #2a56c6;



stringdefault: ''

The label of the button.


booleandefault: false

If true, the button will be styled as a “raised” button.


stringdefault: ''

(optional) The URL of an image for an icon to use in the button. Should not useicon property if you are using this property.


stringdefault: ''

(optional) Specifies the icon name or index in the set of icons available in the icon set. If using this property, load the icon set separately where the icon is used. Should not use src if you are using this property.


Reference: https://www.polymer-project.org/docs/elements/paper-elements.html#paper-button

Learning Polymer


Table of contents


If you want to learn Polymer, the easiest way to get started is to download the starter project:

The starter project includes Polymer, a set of elements, and a starter app. Work through the tutorial for an introduction to Polymer APIs and concepts, or work through the finished app on your own.

If you’re ready to start your own project, you can pick and choose the components you want to install, or install a whole set of components, like the Paper element collection.

Polymer is very modular; you can install just the Polymer library and platform polyfills, a single element, or a whole collection of elements.

Throughout the site, you’ll find component download buttons like this:

The component download button offers three ways to install a component or set of components:

  • Bower. Recommended. Bower manages dependencies, so installing a component also installs any missing dependencies. Bower also handles updating installed components. For more information, seeInstalling with Bower.
  • ZIP file. Includes all dependencies, so you can unzip it and start using it immediately. The ZIP file requires no extra tools, but doesn’t provide a built-in method for updating dependencies. For more information, seeInstalling from ZIP files.
  • Github. When you clone a component from Github, you need to manage all of the dependencies yourself. If you’d like to hack on the project or submit a pull request, see setting up Polymer with git.

Pick your method and follow the instructions in the download dialog.

The recommended way to install Polymer 0.4.0 is through Bower. To install Bower, see the Bower web site.

Bower removes the hassle of dependency management when developing or consuming elements. When you install a component, Bower makes sure any dependencies are installed as well.

If you haven’t created a bower.json file for your application, run this command from the root of your project:

bower init

This generates a basic bower.json file. Some of the questions, like “What kind of modules do you expose,” can be ignored by pressing Enter.

The next step is to install one or more Polymer packages:

bower install --save Polymer/polymer

Bower adds a bower_components/ folder in the root of your project and fills it with Polymer and its dependencies.

Tip: --save adds the item as a dependency in your app’s bower.json: { "name": "my-project", "version": "0.0.0", "dependencies": { "polymer": "Polymer/polymer#~0.4.0" } }

Using the component download button, click the Bower tab and cut and paste the Bower install command.

You can also choose one of the commonly-used packages:

  • Polymer/polymer. Just the Polymer library and platform polyfills.
  • Polymer/core-elements. The Polymer Core elements collection.
  • Polymer/paper-elements. The Paper elements collection.

For example, if you’d like to install Polymer’s collections of pre-built elements, run the following commands from the terminal:

bower install --save Polymer/core-elements
bower install --save Polymer/paper-elements

When a new version of Polymer is available, run bower update in your app directory to update your copy:

bower update

This updates all packages in bower_components/.

When you download a component or component set as a ZIP file, you get all of the dependencies bundled into a single archive. It’s a great way to get started because you don’t need to install any additional tools.

Expand the ZIP file in your project directory to create a components folder.

If you download multiple component sets as ZIP files, you’ll usually end up with multiple copies of some dependencies. You’ll need to merge the contents of the ZIP files.

Unlike Bower, the ZIP file doesn’t provide a built-in method for updating dependencies. You can manually update components with a new ZIP file.

Because there are a number of dependencies we suggest you install Polymer with Bower instead of git. If you’d like to hack on the project or submit a pull request check out our guide on setting up Polymer with git.

Now that you’ve installed Polymer it’s time to learn the core concepts. In the next section we’ll get you up and running on using elements in a project. Continue on to:

If you’d rather skip ahead, check out our guide on Creating Elements.

reference: https://www.polymer-project.org/docs/start/getting-the-code.html

Add Google Cloud Platform as Backend with Android Studio

Android Studio lets you easily add a cloud backend to your application, right from your IDE. A backend allows you to implement functionality such as backing up user data to the cloud, serving content to client apps, real-time interactions, sending push notifications through Google Cloud Messaging for Android (GCM), and more. Additionally, having your application’s backend hosted on Google App Engine means that you can focus on what the cloud application does, without having to worry about administration, reliability or scalability.

When you create a backend using Android Studio, it generates a new App Engine application under the same project, and gives your Android application the necessary libraries and a sample activity to interact with that backend. Support for GCM is built-in, making it easy to sync data across multiple devices. Once you’ve generated the project, you can build and run your client and server code together, in a single environment, and even deploy your backend code right from Android Studio.

In this post we’ll focus on how to get started with the basic setup. From there it’s easy to extend the basic setup to meet your needs.

Preliminary setup
Before you get started, make sure you take care of these tasks first:

Download Android Studio if you haven’t done so already and set it up.
Make sure you have an application project set up in Android Studio. You can use any working app that you want to integrate with your backend, even a sample app.
If you’ll be running the app on an emulator, download the Google APIs Addon from the SDK Manager and run your app on that image.
Create a Google Cloud Platform project: In the Cloud Console, create a new project (or reuse an old one) and make note of the Project ID. Click on the words “Project ID” on the top left to toggle to the Project Number. Copy this as well.
Enable GCM and obtain API Key: In the Cloud Console, click on APIs and turn on the Google Cloud Messaging for Android API. Then, click on the “Register App” button on the top left, enter a name for the app, then select “Android” and “Accessing APIs via a web server”. In the resulting screen, expand the “Server Key” box and copy the API key.
1. Generate an App Engine project
In Android Studio, open an existing Android application that you want to modify, or create a new one. Select the Android app module under the Project node. Then click Tools > Google Cloud Endpoints > Create App Engine Backend.

In the wizard, enter the Project ID, Project Number, and API Key of your Cloud project.

This will create:

An App Engine project which contains the backend application source
An endpoints module with a RegisterActivity class, related resources, and client libraries for the Android app to communicate with the backend
The generated App Engine application (-AppEngine) is an Apache Maven-based project. The Maven pom.xml file takes care of downloading all the dependencies, including the App Engine SDK. This module also contains the following:

A Google Cloud Endpoint (DeviceInfoEndpoint.java, auto-generated from DeviceInfo.java) that your Android app will “register” itself through. Your backend will use that registration info to send a push notification to the device.
A sample endpoint, MessageEndpoint.java, to list previously sent GCM messages and send new ones.
A starter web frontend application (index.html in webapp directory) that will show all the devices that have registered with your service, and a form to send them a GCM notification.
The endpoints module (-endpoints) generated for you contains the classes and libraries needed by the Android application to interact with the backend:

A RegisterActivity.java class that, when invoked, will go through the GCM registration flow and also register itself with the recently created backend through DeviceInfoEndpoint.
Client libraries, so that the application can talk to the backend using an object rather than directly using raw REST calls.
XML files related to the newly created activity.
2. Add GCM registration to your app
In your Android application, you can call RegisterActivity whenever you want the registration to take place (for example, from within the onCreate() method of your main activity.

import android.content.Intent;

protected void onCreate(Bundle savedInstanceState) {

Intent intent = new Intent(this, RegisterActivity.class);
3. Deploy the sample backend server
When you’re ready to deploy an update to your ( the sample ) production backend in the cloud, you can do that easily from the IDE. Click on the “Maven Projects” button on the right edge of the IDE, under Plugins > App Engine, right-click and run the appengine:update goal.

As soon as the update is deployed, you can also access your endpoints through the APIs Explorer at http://.appspot.com/_ah/api/explorer.

For testing and debugging, you can also run your backend server locally without having to deploy your changes to the production backend. To run the backend locally, just set the value of LOCAL_ANDROID_RUN to true in CloudEndpointUtils.java in the App Engine module.

4. Build and run the Android app
Now build and run your Android app. If you called RegisterActivity from within your main activity, the device will register itself with the GCM service and the App Engine app you just deployed. If you are running the app on an emulator, note that GCM functionality requires the Google APIs Addon image, which you can download from the SDK Manager.

You can access your sample web console on any browser at http://.appspot.com. There, you will see that the app you just started has registered with the backend. Fill out the form and send a message to see GCM in action!

Extending the basic setup
It’s easy to expand your cloud services right in Android Studio. You can add new server-side code and through Android Studio instantly generate your own custom endpoints to access those services from your Android app.


What is Google Map Maker?

Google Map Maker allows you to add and update geographic information for millions of users to see in Google Maps and Google Earth. By sharing information about the places you know, like businesses in your town or places in your school campus, you can ensure the map accurately reflects the world around you. Your updates will be reviewed and once approved, will appear online for people from all over the world to see.

You can make edits using Google Map Maker over 188 countries and regions around the world. Start mapping today!

What is map maker satellite view

With Google Map Maker, you can:

  • Add places of interest such as your local restaurants, cafés, schools and more.
  • Edit and update details for existing places.
  • Help avid hikers by mapping trails, be it for a casual walk or an adventurous trip!
  • Get driving directions and also help in making them more accurate.
  • See what your peers are mapping in specific areas.

Getting to know Map Maker

Here’s the basic layout of the Map Maker interface:


Names of top contributers in view port






  1. Viewport: The viewport displays the map that you’re working on. This is where you can add, edit and review features. You can use the navigation controls to zoom in and out or move around the map, and switch between Map and Satellite views. To view stats for top contributors to an area, hover your mouse pointer over the contributors’ names in the right bottom corner of the viewport.
  2. Street View: An orange pegman Orange Pegman indicates that Street View is available; a grey pegmanGrey Pegman indicates that it’s not available. The lower right corner of the viewport has a Street View preview.
  3. Top menu bar: After you’ve signed in, click the gear-shaped icon in the upper-right corner to display links to your Profile and Settings pages. You can also find links to Labs features, the Discussion Forum and the Help Center.
  4. Toolbar: The toolbar is enabled when you zoom in to a particular area. Use it to add features such asPlacesShapes and Lines. You can also use it to find and edit features.
  5. Left panel: Displays information about updates, edits and directions related to the current action you’re performing. Learn more about the left panel workspace.
  6. Searching tools: The search box, along with Browse and Advanced Search will help you find businesses, schools and other places of interest. Learn more about searching.
  7. Location bar: Displays your current location based on the area represented by the viewport. You may need to zoom in to view this information.
  8. Getting Started tool: Click  for guided instructions on how to add, edit, find features and more on Map Maker.

Reference : http://support.google.com/mapmaker/bin/static.py?hl=en&page=guide.cs&guide=30028&topic=1094318&answer=157176

Google Stock API

API Url Formatting

The API from what I can tell is very simple. It only has a single parameter that accepts a stock ticker.

Here’s an example:

It should return:

<?xml version="1.0"?>
<xml_api_reply version="1">
    <finance module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
        <symbol data="AAPL"/>
        <pretty_symbol data="AAPL"/>
        <symbol_lookup_url data="/finance?client=ig&amp;q=AAPL"/>
        <company data="Apple Inc."/>
        <exchange data="Nasdaq"/>
        <exchange_timezone data="ET"/>
        <exchange_utc_offset data="+05:00"/>
        <exchange_closing data="960"/>
        <divisor data="2"/>
        <currency data="USD"/>
        <last data="321.90"/>
        <high data="323.48"/>
        <low data="321.33"/>
        <volume data="3753391"/>
        <avg_volume data="12682"/>
        <market_cap data="295281.14"/>
        <open data="323.00"/>
        <y_close data="323.66"/>
        <change data="-1.76"/>
        <perc_change data="-0.54"/>
        <delay data="0"/>
        <trade_timestamp data="54 seconds ago"/>
        <trade_date_utc data="20101231"/>
        <trade_time_utc data="184724"/>
        <current_date_utc data="20101231"/>
        <current_time_utc data="184818"/>
        <symbol_url data="/finance?client=ig&amp;q=AAPL"/>
        <chart_url data="/finance/chart?q=NASDAQ:AAPL&amp;tlf=12"/>
        <disclaimer_url data="/help/stock_disclaimer.html"/>
        <ecn_url data=""/>
        <isld_last data="323.00"/>
        <isld_trade_date_utc data="20101231"/>
        <isld_trade_time_utc data="143001"/>
        <brut_last data=""/>
        <brut_trade_date_utc data=""/>
        <brut_trade_time_utc data=""/>
        <daylight_savings data="false"/>

As you can see it’s nice simple XML, very well formated, so it’s makes getting the data out a snap.

ASP.NET Example

Here is a quick example of using the Google Stock API with your ASP.NET C# apps. This example has only a single page and a quick form. You enter the stock symbol into the box and click the button and it will return the details via the Google Stock API.

Default.aspx ASP.NET Code

<%@ Page Title="Home Page" Language="C#"  AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="GoogleStockApi.Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <form id="getQuote" runat="server">
        <h1>Stock Quote Service</h1>
        <asp:Label Text="Enter a symbol to lookup:" />
        <asp:TextBox id="symbol" runat="server" />
        <asp:Button Text="Get Quote" runat="server" />
        <div>Company: <%=Company %></div>
        <div>Company: <%=Exchange %></div>
        <div>High: <%=High %></div>
        <div>Low: <%=Low %></div>
        <div>Last: <%=Last %></div>

Default.aspx.cs C# Code

using System;
using System.Web.UI;
using System.Xml.Linq;
namespace GoogleStockApi
    public partial class Default : Page
        public string Company { get; set; }
        public string Exchange { get; set; }
        public double Last { get; set; }
        public double High { get; set; }
        public double Low { get; set; }
        protected void Page_Load(object sender, EventArgs e)
            if (Request.Form["symbol"] != null)
                string symbol = Request.Form["symbol"];
        private void FetchQuote(string symbol)
            string url = "http://www.google.com/ig/api?stock=" + Server.UrlEncode(symbol);
            XDocument doc = XDocument.Load(url);
            Company = GetData(doc, "company");
            Exchange = GetData(doc, "exchange");
            Last = Convert.ToDouble(GetData(doc, "last"));
            High = Convert.ToDouble(GetData(doc, "high"));
            Low = Convert.ToDouble(GetData(doc, "low"));
        private string GetData(XDocument doc, string name)
            return doc.Root.Element("finance").Element(name).Attribute("data").Value;

Find the Latitude Longitude Of Your Home with Google Maps

Q: How to find the latitude and longitude coordinates of a place when you either have the street address or the zip code or just the name of a city.

Following are steps involved:

1. Open the Google Maps website and enter the address details in the search box.

2. Zoom In the Google Maps as much as possible until you locate the place for which you need the latitude and longitude.

3. Right click that exact location on Google Maps and select “Center Map Here”

4. Click the “Link to this Page” hyperlink on Google Maps website and copy paste the URL into notepad – look for the value of ll parameter in the URL – they are the latitude and longitude coordinates of your home.


Copy paste that value in the Google Maps Search box again to confirm the location on Google Maps.



How to Create a Mashup by Combining 3 Different APIs

This tutorial will show you how to create a mashup of three different APIs including integration with Google Maps. This idea came about when I was searching through ProgrammableWeb’s API directory for a couple APIs that complimented each other enough that I could use one to provide the other with data. What I came up with will be known as the “Beer Mashup”.

Step 1. API Discovery

While looking through ProgrammableWeb’s directory, I found an IP geolocating tool called ipLoc. It simply accepts in an IP address and returns relevant location-specific data on it such as it’s state, city, country, postal code, etc.

I then found the very cool Beer Mapping Project, which has a huge directory of bars and pubs from not only across the US, but many other countries as well. Instantly I noticed that this was a perfect compliment to ipLoc because the BeerMapping API requires a city (which we can get from the ipLoc API) to return a list of local bars and pubs.

Lastly, I also wanted to integrate Google Maps into this mashup to plot out the addresses of the bars and pubs to add a bit of interactivity to the page instead of just displaying each bar in a simple HTML list.

Step 2. Variable Initialization

I usually find it best to start PHP documents off with some of the variables that I want to set globally within the script. Here I add a line that silences PHP warning messages (Google Maps spits out many of these if you happen to try to map an invalid address) and my BeerMashup and Google Maps API keys. We will end up using these API keys when we get to their respective steps below.

	<li> error_reporting(E_ERROR|E_PARSE);  //Silence Errors</li>
	<li>//Initialize Variables</li>
	<li> $beer_api = 'YOUR_BEERMAPPING_API_KEY';</li>
	<li> $gmaps_api = 'YOUR_GOOGLEMAPS_API_KEY';</li>

Step 3. IP Geolocation Setup

The ipLoc API allows you to either specify an IP address to get data on, or use the default IP address that the script finds.

Default Version: http://iploc.mwudka.com/iploc/json/
Static Version (IP address is hardcoded): http://iploc.mwudka.com/iploc/

  1. //Set Location
  2. //Visitor IP Address
  3. $ip = getenv(“REMOTE_ADDR”);
  4. //via IPLoc
  5. $iploc = file_get_contents(“http://iploc.mwudka.com/iploc/$ip/json/&#8221;);  //Format: JSON
  6. $ipdata = json_decode($iploc, true);

After a little testing, I realized that the default version of the ipLoc API was finding the location (Scottsdale, AZ, USA) of my hosting provider’s server rather than my home computer’s IP location (Pittsburgh, PA, USA). To circumvent this, I decided to use the static IP version of the API (Line 2 above) and passed in the IP address that is detected by the getenv(“REMOTE_ADDR”) php variable.

After checking if the data has been successfully returned as a decoded json formatted string, we need to extract only the specific data we want to pass to the BeerMapping API, which is the city and state.

  1. // Error checking
  2. if ($ipdata[‘city’]) {
  3. $city = $ipdata[‘city’];
  4. $state = $ipdata[‘region’];
  5. $location = $city .”, “. $state;
  6. } else {
  7. $err = “No location data returned for your IP address: “. $ip;
  8. }

Step 4. Integrating Google Maps

This step needs to be done now because the next step will add the location points to Google Maps – and Google Maps has to be initialized before any of that can happen.

To make the Google Maps integration as easy and painless as possible, I’ve enlisted the help of a great PHP class called Phoogle from System Seven Designs. This class takes care of all the Google Maps API heavy lifting for us while just allowing us to worry about the data.

All we need to do to get this to work is to first include the class file we downloaded: phoogle.php, then set some basic map parameters such as the height, width, zoom level and your Google Maps API key. (Get one of those here).

  1. //Phoogle – GoogleMaps PHP Class
  2. require_once ‘phoogle.php’;
  3. $map = new PhoogleMap();
  4. $map->setAPIKey($gmaps_api); //Using the variable we set in Step 2
  5. $map->setHeight(450);
  6. $map->setWidth(750);
  7. $map->zoomLevel = 6;
  8. $map->showType = false;

Step 5. BeerMapping API

Since we have the combined city and state in the variable $location from Step 3, we have everything we need to pull data from the BeerMapping API. Of course we also need one of their API keys, which can be requested here (about a 30 seconds process, start to finish).

A BeerMapping API call looks like this according to their examples:
Real Example:http://beermapping.com/webservice/loccity/71515667a86b8ec7f58cd22e3af86f6e/pittsburgh,pa

After substituting our variables in for the API Key (Step 2) and Location (Step 3), our BeerMapping API call now looks like this:
Our Example: http://beermapping.com/webservice/loccity/$beer_api/$location

After a little playing around with this API, I found that the location can’t have any spaces. So the below code first gets rid of the space bewtween the “city, state” format. Then it replaces all other spaces within the location with underscores “_”.

  1. //Format Location for use with API
  2. $locationF = str_replace(“, “, “,”, $location); // Remove space before “State”
  3. $locationF = str_replace(” “, “_”, $locationF); // Replace space with underscore in “City” name

Their data can only be returned in xml format, so we can easily extract the data returned by this call with thesimplexml_load_file PHP function.

  1. //BeerMapping – Format: XML
  2. $beerdata = simplexml_load_file (“http://beermapping.com/webservice/loccity/$beer_api/$locationF&#8221;);

As the image shows, we first load the whole file into the variable $beerdata. After checking to see if we returned any results…

  1. // Error checking
  2. $beererr = $beerdata->location->id; //$beererr will be 0 if there were no locations returned
  3. if ($beererr == ‘0’) {
  4. $err = “No breweries were found in “. $location;
  5. } else {

…the next step is to cycle through each bar/pub returned in the call, extracting all the data we need to pass into Google Maps (Step 4).

  1. $breweries = $beerdata->location;
  2. $barcount = count($breweries); //How Many?
  3. foreach ($breweries as $brewery) {
  4. $name = $brewery->name;
  5. $link = $brewery->reviewlink;
  6. $street = $brewery->street;
  7. $city = $brewery->city;
  8. $state = $brewery->state;
  9. $zip = $brewery->zip;
  10. $phone = $brewery->phone;
  11. //Location Point set for the Google Maps API
  12. $map->addAddress(“$street $city $state $zip”, “<a href=’$link’ title=’$name BeerMap’>$name</a><br/>$street<br />$city, $state $zip<br />Phone: $phone”);
  13. }
  14. }
  15. ?>

Line 1 above sets the structure location of the “locations”. Line 2 counts the amount of “locations” the API result returned. The remaining lines use a foreach loop to cycle though each “location” and pull out it’s address information. Line 14 sets a “point” for each brewery on our Google Map.

Step 6. HTML Generation

After finishing all the PHP code that we’ve created, we can now work on displaying it. The first few lines shown below are standard in any HTML document, but after that we get back to using PHP. We first check to see if the variable $err is FALSE – which would mean that the $err variable is empty, or that we never received an error. If we never got an error, we spit out the Google Map, otherwise we spit out an error message.

  1. <html xmlns=”http://www.w3.org/1999/xhtml”&gt;
  2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;
  3. <head>
  4. <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
  5. <link rel=”stylesheet” type=”text/css” href=”styles.css” />
  6. <title>Bars Near <?php echo $location; ?></title>
  7. </head>
  8. <body>
  9. <div class=”wrapper”>
  10. <div class=”header”>
  11. <img class=”logo” src=”images/logo.png” alt=”The Beer Mashup” />
  12. <p class=”footer”>Developed by <a href=”http://www.cagintranet.com”>Chris Cagle</a> for <a href=”http://www.nettuts.com”>NETTUTS</a></p&gt;
  13. <div class=”mapdiv”>
  14. <?php
  15. if (!$err) {
  16. echo “<div>”;
  17. $map->printGoogleJS();
  18. $map->showMap();
  19. echo “<h3>”. $location .” <span>(“. $barcount .” Bars)</span></h3>”;
  20. } else {
  21. echo “<p class=\”error\”><b>”. $err .”</b></p>”;;
  22. }
  23. ?>
  24. </div>
  25. </div>
  26. </div>
  27. </body>
  28. </html>

After adding in some text and CSS and you now have a great looking web page that displays all the bars and pubs within the vicinity of the location of whoever is viewing the web page.

View the demo of the page as it stands now. The mashup is working great now, but we have one more improvement that will make all the difference when it comes to UI.

Step 7. Changing the Code to Allow Locations to be Input by the Visitor

At this point, our page works just fine but there is one small caveat: The visitor can only view bars from his or her current location. What if the visitor wants research bars in a different town rather than the one our IP API returned for him or her? Any visitor would want the ability to specify the location to research in.

To allow this, we will have a simple form that will accept in a city and state from the visitor then reload the page for the given location and skip the ipLoc API call completely. We will insert this code right before our<div class=”mapdiv”> line in Step 6.

  1. <form method=”post” id=”form” action=”beermashup2.php”>
  2. <span>location: (ex. New Orleans, LA)</span>
  3. <input type=”text” value=”” name=”loc” id=”loc” /><br class=”clear” />
  4. <input type=”submit” id=”submitted” value=”SEARCH” name=”submitted” />
  5. </form>

In order to make this work, we will need to wrap the code we made in the ipLoc step (Step 3) in an if-statement that checks if the form was submitted or not. If the form *was not* submitted (which will happen each time the page is initially loaded), then it will use the ipLoc IP geolocation code. If the form *was* submitted, it will take what the user submitted and set our $location variable to that.

  1. //Set Location
  2. if ( isset($_POST[‘loc’]) ) {
  3. //via user input
  4. $location = $_POST[‘loc’];
  5. } else {
  6. //Visitor IP Address
  7. $ip = getenv(“REMOTE_ADDR”);
  8. //via IPLoc
  9. $iploc = file_get_contents(“http://iploc.mwudka.com/iploc/$ip/json/&#8221;);  //Format: JSON
  10. $ipdata = json_decode($iploc, true);
  11. // Error checking
  12. if ($ipdata[‘city’]) {
  13. $city = $ipdata[‘city’];
  14. $state = $ipdata[‘region’];
  15. $location = $city .”, “. $state;
  16. } else {
  17. $err = “No location data returned for your IP address: “. $ip;
  18. }

Step 8. Putting it all Together

View the demo of the final application.

You can view the source code of the final project (which is pretty much just the steps above pushed together) and see how I ended up combining 3 separate APIs into one application. Take a stroll for yourself through the API directory over at ProgrammableWeb and see what you can come up with on your own. Working with APIs is my new obsession because it is exciting to be able to create something new and useful from someone else’s data. If this tutorial has helped you mashup a couple of APIs, post them here – I would love to see them.