Solved

Google maps jQuery: how to geocode based on address

Posted on 2013-12-15
7
760 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:greenerpastures
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks
0
 
LVL 38

Expert Comment

by:Tom Beck
Comment Utility
You're welcome, thanks for the points.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
The viewer will learn how to dynamically set the form action using jQuery.
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)

771 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

12 Experts available now in Live!

Get 1:1 Help Now