Solved

Google maps jQuery: how to geocode based on address

Posted on 2013-12-15
7
769 Views
Last Modified: 2013-12-20
I am implementing Google maps with street view using this example:

http://jquery-ui-map.googlecode.com/svn../trunk/demos/jquery-google-maps-streetview.html

It requires lat/long attributes, but my database of listings only has addresses. I can get the address from the URL in various formats:

<?php
$address = $_GET["address"]; //will return entire address like 1 main st denver, co
//or
$location = $_GET["location"]; // 1 main st
$city = $_GET["city"]; // denver
$state = $_GET["state"]; // co
$country = $_GET["country"]; // us
?>

1. Can I somehow use Google API with my API key and with additional code convert address on the fly to lat /long?
Some of my listings already have lat / long info and I can pass and get it from the URL as well.

2. Also need to show map controls: zoom, Hydric view, etc in the example above.
0
Comment
Question by:greenerpastures
  • 4
  • 3
7 Comments
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39720410
The sample at the link you provided is using Google Maps API v2. You definitely want to go with v3. Also, there's no need for jquery plugins to create Google Maps. It easier just using the Google Maps API directly with javascript. Tons of examples online. Lastly, v3 does not require an API key for simple requests.

Here's a example of geocoding addresses into markers on a map. In this case, the addresses are in an array but could easily be pulled from a database. It should be enough to get you started.
   <!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
    <style type="text/css">
      html { height: 100% }
        body { height: 100%; margin: 0; padding: 0 }
        #map-canvas { height: 60%; width: 80% }
      </style>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false&v=3&libraries=geometry" type="text/javascript"></script>

    <script>
      $(document).ready(function() {

            var startingPoint = 123;
            var bounds = new google.maps.LatLngBounds();
            var locations = [
                  {
                        address: '48 W Seegers Rd, Arlington Heights, IL 60005',
                        company: 'Company B'
                  },
                  {
                        address: '220 N Michigan Ave, Chicago, IL 60601',
                        company: 'Company A'
                  },
                  {
                        address: '1670 Barclay Blvd, Buffalo Grove, IL 60089',
                        company: 'Company C'
                  },
                  {
                        address: '1665 Elk Blvd, Des Plaines, IL 60016',
                        company: 'Company D'
                  },
                  {
                        address: '1800 W Central Rd, Mount Prospect, IL 60056',
                        company: 'Company E'
                  },
                  {
                        address: '3400 Dundee Rd, Northbrook, IL 60062',
                        company: 'Company F'
                  },
                  {
                        address: '3100 Dundee Rd Ste 704, Northbrook, IL 60062',
                        company: 'Company G'
                  },
                  {
                        address: '188 W Randolph St Ste 600, Chicago, IL 60601',
                        company: 'Company H'
                  },
                  {
                        address: '69 W Washington St, Chicago, IL 60602',
                        company: 'Company I'
                  },
                  {
                        address: '69 W Washington St, Chicago, IL 60602',
                        company: 'Company J'
                  }
            ];

            var map = new google.maps.Map(document.getElementById('map-canvas'));

            var geocoder = new google.maps.Geocoder();
                  geocoder.geocode({'address': 'USA'}, function(results, status) {
                  map.fitBounds(results[0].geometry.viewport);
                  setDefaultAddress('1061 W Jackson Blvd, Chicago, IL 60607');
            });

            var chunk = 0;
			// muliple location geocoding needs to be done on a delay as Google restricts the number of
			// consecutive geocode requests
            var inerval = setInterval(delayCode, 700);
            function delayCode() {
				if(startingPoint != 123){
                  var step = 1;
                  if (chunk < locations.length) {
                        for (x = chunk; x < locations.length && x < chunk + step; x++) {
                              codeAddress(locations[x]);
                        }
                        chunk += step;
                  } else{
                        clearInterval(inerval);
                  }
				}
            }

            function setDefaultAddress(address) {
                  var geocoder = new google.maps.Geocoder();
                  geocoder.geocode({'address': address}, function(results, status) {
                        if(status == google.maps.GeocoderStatus.OK) {
                              result = results[0].geometry.location;
                              startingPoint = result;
                              var mapOptions = {
                                    zoom: 15,
                                    center: startingPoint,
                                    mapTypeId: google.maps.MapTypeId.ROADMAP
                              }

                              map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
                              var marker = new google.maps.Marker({
                                    map: map,
                                    icon: "http://www.conceptfire-uk.com/wp-content/uploads/2011/07/icon-pin-color.png",
                                    position: startingPoint
                              });
                        }
                        else {
                              alert("Unable to find address: " + status);
                        }
                  });
				  bounds.extend(startingPoint);
            }

            function codeAddress(address) {
                  geocoder.geocode({ 'address':address.address }, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                        var location = results[0].geometry.location;
                        address.location = location;
						createMarker(address);
                        }
                        else {
                              alert('Geocode was not successful for the following reason: ' + status);
                        }
                  });
            }

			function createMarker(loc){
				var marker = new google.maps.Marker({map: map, position: loc.location, title: loc.company, address: loc.address});
				var infowindow = new google.maps.InfoWindow();
			      google.maps.event.addListener(marker, "click", function () {
                	  infowindow.setContent('<b>' + this.title + '</b><br />' + this.address);
                	  infowindow.open(map, this);
            	  });
				  
				  //extend the bounds of the map to include the two closest markers and the starting point
				  bounds.extend(loc.location);
				  
				  //zoom the map to nicely fit the bounds of the two closest markers and the starting point
                  map.fitBounds(bounds);
			}
	  });
    </script>
    
  </head>
  <body>
  	    <div id="map-canvas"></div>
  </body>
</html>

Open in new window

Hydric view? Do you mean Hybrid?
0
 

Author Comment

by:greenerpastures
ID: 39724414
Hi,
I thought my jQuery example was based on Google Api V 3 as it states at the top of that page, but I could be wrong.
I tried you code and it works on its one, but the map does not appear if the <div id="map-canvas"></div> is wrapped in another div--which is strange, like below:

<body>
      
<div class="123">
      
 <div id="map-canvas"></div>
 </div>      
      </body>
</html>

I'm inserting the maps into existing pages it will be wrapped in other div's as part of the template. Would you know how to correct this?

Also, some of my listings have lat/long info, is there a way to modify the code in the head above so I could pass either the address or lat / long info? Thanks
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39724899
The code in the example is Google Maps API v2. The give away is the use of "gmap" instead of "Map". The page is advertising a jQuery plugin for creating a Google Map. The plugin version is 3.0. I would stay clear of that, especially if it uses v2 of the API.

If some locations are provided as longitude/latitude pairs, you would just need to check which it is and direct the script accordingly. With longitude/latitude pairs there's no need for geocoding so you can bypass that part in those instances.

Having the map-canvas div inside another div would not prevent the map from displaying. The map will not display however, if you do not have a width and height defined for the map-canvas div. Could that be the issue?

I should be in front of a computer again this evening. If no one else responds by then I can modify the script.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:greenerpastures
ID: 39725295
OK, the div problem is solved after the width and height are defined, thanks.
Could you also suggest how to show the street view based on the same data, just below <div id="map-canvas"></div> ?

And if the street view is not available could the script "fail gracefully" by just showing blank space?
0
 
LVL 38

Accepted Solution

by:
Tom Beck earned 500 total points
ID: 39725712
New sample. Shows street view below the map only when it's available. Places markers either by longitude/latitude pairs or by address based on the data presented.
   <!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Google Maps JavaScript API v3 Example: Geocoding with Street View</title>
    <style type="text/css">
      html { height: 100% }
        body { height: 1000px; margin: 0; padding: 0 }
        #map-canvas { height: 48%; width: 80% }
		#pano { height: 48%; width: 80% }
      </style>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false&v=3&libraries=geometry" type="text/javascript"></script>

    
  </head>
  <body>
  	    <div id="map-canvas"></div>
		<div id="pano"></div>
        
    <script>
            var bounds = new google.maps.LatLngBounds();
			var geocoder = new google.maps.Geocoder();
			var sv = new google.maps.StreetViewService();
            var locations = [
                  {
                        address: '48 W Seegers Rd, Arlington Heights, IL 60005',
                        company: 'Company B',
						latlng:  ''
                  },
                  {
                        address: '220 N Michigan Ave, Chicago, IL 60601',
                        company: 'Company A',
						latlng:  ''
                  },
                  {
                        address: '1670 Barclay Blvd, Buffalo Grove, IL 60089',
                        company: 'Company C',
						latlng:  ''
                  },
                  {
                        address: '',
                        company: 'Company D',
						latlng:  '42.04473,-87.88300'
                  },
                  {
                        address: '1800 W Central Rd, Mount Prospect, IL 60056',
                        company: 'Company E',
						latlng:  ''
                  },
                  {
                        address: '',
                        company: 'Company F',
						latlng:  '42.13889,-87.86288'
                  },
                  {
                        address: '3100 Dundee Rd Ste 704, Northbrook, IL 60062',
                        company: 'Company G',
						latlng:  ''
                  },
                  {
                        address: '188 W Randolph St Ste 600, Chicago, IL 60601',
                        company: 'Company H',
						latlng:  ''
                  },
                  {
                        address: '69 W Washington St, Chicago, IL 60602',
                        company: 'Company I',
						latlng:  ''
                  },
                  {
                        address: '',
                        company: 'Company J',
						latlng:  '41.88318,-87.63173'
                  }
            ];

            var startingPoint = new google.maps.LatLng(41.88318,-87.63173);
		    var mapOptions = {
            	zoom: 15,
                center: startingPoint,
                mapTypeId: google.maps.MapTypeId.ROADMAP
             }

             var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
             var marker = new google.maps.Marker({
                map: map,
                icon: "http://www.conceptfire-uk.com/wp-content/uploads/2011/07/icon-pin-color.png",
                position: startingPoint
             });
			 var panoramaOptions = {
  				position: startingPoint,
  				pov: {
    				heading: 34,
    				pitch: 10
  				}
			  };
			  var panorama = new  google.maps.StreetViewPanorama(document.getElementById("pano"), panoramaOptions);
              map.setStreetView(panorama);

            var chunk = 0;
			// muliple location geocoding needs to be done on a delay as Google restricts the number of
			// consecutive geocode requests
            var inerval = setInterval(delayCode, 700);
            function delayCode() {
                  var step = 1;
                  if (chunk < locations.length) {
                        for (x = chunk; x < locations.length && x < chunk + step; x++) {
                              codeAddress(locations[x]);
                        }
                        chunk += step;
                  } else{
                        clearInterval(inerval);
                  }
            }

            function codeAddress(address) {
			   if (address.address !== '') {
                  geocoder.geocode({ 'address':address.address }, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                        	address.location = results[0].geometry.location;							
			   	            createMarker(address);
                        }
                        else {
                            console.log('Geocode was not successful for the following reason: ' + status);
                        }
                  });
			   } else if (address.latlng !== '') {
				   var latlngPair = address.latlng.split(',');
				   address.location = new google.maps.LatLng(parseFloat(latlngPair[0]), parseFloat(latlngPair[1]));				   
			   	   createMarker(address);
			   }
            }

			function createMarker(loc){
				var marker = new google.maps.Marker({map: map, position: loc.location, title: loc.company, address: loc.address, location: loc.latlng});
				var infowindow = new google.maps.InfoWindow();
			      google.maps.event.addListener(marker, "click", function () {
                	  infowindow.setContent('<b>' + this.title + '</b><br />' + this.address + this.location);
                	  infowindow.open(map, this);
					  sv.getPanoramaByLocation(this.position, 50, function(data, status){
						  if (status == google.maps.StreetViewStatus.OK) {
							  panorama.setPano(data.location.pano);
							  document.getElementById('pano').style.visibility = 'visible';
						  } else {
							  document.getElementById('pano').style.visibility = 'hidden';
							  alert('Street View data not found for this location.');
						  }
					  });
            	  });
				  
				  //extend the bounds of the map to include the two closest markers and the starting point
				  bounds.extend(loc.location);
				  
				  //zoom the map to nicely fit the bounds of the two closest markers and the starting point
                  map.fitBounds(bounds);
			}
			
			
    </script>
  </body>
</html>

Open in new window

0
 

Author Closing Comment

by:greenerpastures
ID: 39731110
Thanks
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39731565
You're welcome, thanks for the points.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now