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.

http://maps.google.com/maps?q=san+francisco&ll=17.421306,78.457553

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

latitude-longitude-hyderabad

 

Advertisements

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.

<ol>
	<li>&lt;?php</li>
	<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>
</ol>

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/68.162.155.110/json/

  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.

This is How You Use the Google Maps API – screencast

So your client emails you and asks, “Can you put one of those flashy maps on my contact page so that users can actually see our building from a satellite’s view?”. You’ve used Google maps many times, but there is only one problem: you have no idea how to use the API. Well get out your spoon and dig in!

Step 1: Obtain a Unique API Key

If you were to download the source code that is provided with this article, you would find that it doesn’t work on your website. The reason is because Google requires all users to obtain a unique “API key” for each site that implements Google maps.

Never fear. It’s 100% free and takes about thirty seconds to sign up. First, visit Google’s sign up page and enter the url of your website. Don’t worry about adding a specific path. The root url will cover every page that is part of that domain. Agree to the terms and conditions and click “Generate API”.

Generate Key

That’s it! The page that you’ve been redirected to contains your unique key as well as a sample page – to serve as a crash course. Your key will look something like:

ABQIAAAAAq93o5nn5Q3TYaaSmVsHhR1DJfR2IAi0TSZmrrsgSOYoGgsxBSG2a3MNFcUDaRPk6tAEpdWI5Odv

You’ll also find a script path that will look like:

Yours will be different from mine because it will contain your own specific key value. Copy this and paste it into the head portion of your document.

Sign Up Complete

You might want to bookmark the link to the API documentation. You’ll undoubtedly be referencing it as your skills progress.

Step 2: Setting Up Your HTML

For the sake of simplicity, we’ll create a bare bones layout. Add the following within the body element of your document.

  1. <div id=”myMap” style=”width: 600px; height: 400px;”></div>

In a real world situation, you should move the styling to an external file (like I did in the video). The height and width values will by used by the API to determine the dimensions of your map. Don’t worry, nothing will be clipped off.

Step 3: Javascript

Next, add the following to your Javascript file. Review it a bit and then continue on.

  1. $(function() { // when the document is ready to be manipulated.
  2. if (GBrowserIsCompatible()) { // if the browser is compatible with Google Map’s
  3. var map = document.getElementById(“myMap”); // Get div element
  4. var m = new GMap2(map); // new instance of the GMap2 class and pass in our div location.
  5. m.setCenter(new GLatLng(36.158887, -86.782056), 13); // pass in latitude, longitude, and zoom level.
  6. }
  7. else {alert(“Your browser is not worthy.”);}
  8. });

To take this code line by line:

  • When the document is ready to be manipulated, run the code within.This is a jQuery syntax, but jQuery isn’t required in the least. You could also simply add an “onLoad()” attribute to your body element – though this is messy.
  • If the browser that the user is accessing the map from isn’t compatible with the API, then show an alert (see bottom). Otherwise, run the code within.
  • Create a variable called “map” and tell it to find the div that will contain the map.
  • Next, create a variable called “m” and make it equal to a new instance of the “GMap2″ class. Within the parenthesis, pass in the “map” variable that you just created previously
  • Finally, set a center point so that the map knows what to show. To do this, we create a new instance of the “GLatLng” class and pass in the latitude and longitude values. You can go here to grab the appropriate values. In my case, I’ve set the coordinates to my home town. After that, you can optionally input a zoom level – which I’ve set to the standard ’13′.

This code alone will give you a basic map that might be completely appropriate for your needs. However, if you’d like to also implement “zoom” and “map mode” features, read on.

Step 4: Refining Our Map

There are literally dozens of features that you can add to your map. We’ll go over a few of them. First, we’ll implement a zoom bar that will allows the users to incrementally zoom in or out.

Layout
  1. m.addControl(new GLargeMapControl())

Here, we’re taking our map and are adding a new control called “GLargeMapControl”.

Next, let’s add a feature that will allow the users to choose which map mode they desire – Normal, Satellite View, or a hybrid.

  1. var c = new GMapTypeControl(); // switch map modes
  2. m.addControl(c);
  • Create a variable called “c” and make it equal to a new instance of the “GMapTypeControl” class.
  • Add a new control, and pass in “c”.

If you refresh your browser, you’ll see that the user nows has the option to choose his viewing mode. But what if you want to set the default mode? In such instances, you would use “setMapType”.

  1. m.setMapType(G_SATELLITE_MAP);

When defining the default mode, you have three choices.

  • G_SATELLITE_MAP
  • G_NORMAL_MAP
  • G_HYBRID_MAP

You’re Finished!

That wasn’t too hard, was it? There are a few specific class names that you’ll need to memorize, or jot down for later reference. But other than that, it’s strikingly simple to implement such an advanced map into your websites.