Ecommerce Developer
 
 

APIs & Plug-ins

Develop a Store Finder with the Google Maps API, Part 7: Driving Directions

 

A common feature on multi-channel retail sites is store finder. In the past several weeks this series has described how to build just such a store finder using Google's JavaScript Maps API, PHP, MySQL, JavaScript, and some basic HTML and CSS.

So far in the series, I've described how I set up the MySQL database with geolocated store data and then query that database for the nearest store to a given location (Part 1); how to return the query results as XML (Part 2); how to code the JavaScript to capture a user submitted address and initiate the API (Part 3); how to make an Ajax call (Part 4); how to display the Ajax query results (Part 5); and how to add custom markers to the Google map (Part 6).

Now it's time to add driving directions for the first address on the list.

As a reminder, for my example store finder, I am locating Dutch Bros. drive-through coffee shops in my home state of Idaho.

screen capture of the store finder

Step No. 15: Add Driving Directions

I want to do more than return a list of nearby stores. I also want to provide driving directions to the nearest Dutch Bros. To do this I need to add a conditional statement to my JavaScript.

In particular, I am going to be working on the function nearStepFour(). To help provide context, I've included this function below.

unction nearStepFour(data){
	var googleMap = document.createElement('div');
	googleMap.id = 'Google-Map';
	var parentDiv = document.getElementById('content');
	parentDiv.appendChild(googleMap);
	

	var xml = parseXml(data);
	var eachStore = xml.documentElement.getElementsByTagName('store');

	map = new google.maps.Map(document.getElementById('Google-Map'), {
        center: new google.maps.LatLng(parseFloat(eachStore[0].getAttribute('latitude')), parseFloat(eachStore[0].getAttribute('longitude'))),
        zoom: 13,
        mapTypeId: 'roadmap',
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
      });

	
	
	for(var i = 0; i < eachStore.length; i++){
		var store = eachStore[i].getAttribute('store_name');
		var street = eachStore[i].getAttribute('street');
		var city = eachStore[i].getAttribute('city');
		var state = eachStore[i].getAttribute('state');
		var zip = eachStore[i].getAttribute('zip');
		var latitude = eachStore[i].getAttribute('latitude');
		var longitude = eachStore[i].getAttribute('longitude');
		var distance = eachStore[i].getAttribute('distance');
		
		var storeInfo = document.createElement('div');
		storeInfo.id = 'store-info' + [i];
		storeInfo.innerHTML = '<ul><li>' + store + '</li><li>' + street + '</li><li>' + city + ', ' + state + ' ' + zip + '</li></ul>';
		parentDiv.appendChild(storeInfo);
		
		makeMarker(latitude,longitude);
	}


}

My new code will be added at the bottom of this function, but still inside of the for loop.

if(i == 0){
			var directionsSection = document.createElement('div');
			directionsSection.id = 'store-directions';
			directionsSection.innerHTML = '<h6>Directions...</h6>';
			document.getElementById('store-info0').appendChild(directionsSection);
			directions = new google.maps.DirectionsService();
			var showDirections = new google.maps.DirectionsRenderer();
			var findRoute = {origin: cusStartAddress, destination: new google.maps.LatLng(latitude, longitude), travelMode: google.maps.DirectionsTravelMode.DRIVING, unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL};
			directions.route(findRoute, function(response, status){
				if(status == google.maps.DirectionsStatus.OK){
					showDirections.setPanel(document.getElementById('store-directions'));
					showDirections.setDirections(response);
				}
			});
			
		}

Now, let's take this line-by-line.

I start by declaring the conditional statement. In this case, the conditional is only true if the first result ("0" in zero-based counting) is the one moving through the loop.

if(i == 0){

Next, I create a new div element. This element will ultimately hold the actual driving directions.

var directionsSection = document.createElement('div');
directionsSection.id = 'store-directions';
directionsSection.innerHTML = '<h6>Directions...</h6>';
document.getElementById('store-info0').appendChild(directionsSection);

I use the Google Maps API to get the actual directions.

directions = new google.maps.DirectionsService();
var showDirections = new google.maps.DirectionsRenderer();
var findRoute = {origin: cusStartAddress, destination: new google.maps.LatLng(latitude, longitude), travelMode: google.maps.DirectionsTravelMode.DRIVING, unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL};
			directions.route(findRoute, function(response, status){
				if(status == google.maps.DirectionsStatus.OK){
					showDirections.setPanel(document.getElementById('store-directions'));
					showDirections.setDirections(response);
				}
			});
			
		}

Notice that I need to initiate both a directions service and a directions renderer from the API.

directions = new google.maps.DirectionsService();
var showDirections = new google.maps.DirectionsRenderer();

I also used a variable, findRoute, to store the options for my directions service. This is not strictly required. But since directions.route is also going to include an anonymous function, using the variable makes the code much cleaner.

var findRoute = {origin: cusStartAddress, destination: new google.maps.LatLng(latitude, longitude), travelMode: google.maps.DirectionsTravelMode.DRIVING, unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL};
directions.route(findRoute, function(response, status){

Finally, I check to ensure that my application was able to get directions back from the API before trying to add anything to the page.

if(status == google.maps.DirectionsStatus.OK){
	showDirections.setPanel(document.getElementById('store-directions'));
	showDirections.setDirections(response);
}

screen capture of the directions

Summing Up

Functionally, my Dutch Bros. store finder is complete. A user can submit an address and see a list of nearby Dutch Bros. locations, a map with custom Dutch Bros. markers, and even driving directions to the nearest location.

screen capture of the app with directions

In a real world application, you'll want to add some CSS to finish the layout. If you do use this tutorial series to build a store finder, please let us know in the comments below.

Related Articles

Search Terms

7 Comments

Rss-sm