Skip to content

Dynamic Directions Requestions

Justin Kimbrell edited this page Sep 1, 2014 · 5 revisions

At times you may be required to output directions within a template dynamically. Whether it's a details page with directions, or a directions form for user, the process is relatively quick and easy with Google Maps for Craft. The concept here is that you send a request to Google Maps Directions API. What you do with the response is up to you, but it's possible to output a list of HTML, meta data, or even plot the route on a map. Everything returned in the Sample Response is available within the template.

{% set options = {
	id: 'map', 
	width: '400px', 
	height: '300px',
	options: {
		disableDoubleClickZoom: true,
		maxZoom: 10
	}
} %}

{{ craft.googleMaps.map(options) }}

{% set response = craft.googleMaps.directions({
	origin: 'Indianapolis, IN',
	destination: 'Florida',
	waypoints: [
		'Texas',
		'Arkansas'
	],
	language: 'en',
	avoidFerries: false,
	avoidHighways: false,
	avoidTolls: false,
	optimizeWaypoints: false,
	provideRouteAlternatives: false,
	travelMode: 'DRIVING',
	region: 'us',
	unitSystem: 1
}) %}

{{ response.plot('map') }}

{% for route in response.routes %}

	<p><b>Summary</b><br> {{ route.summary }}</p>

	<p><b>Directions</b></p>

	{% for leg in route.legs %}

		<p>Total Duration ({{ leg.duration.text }} - {{leg.distance.text}})</p>

		<p>
			<b>Starting Address:</b> {{ leg.start_address }}<br>
			<b>Ending Address:</b> {{ leg.end_address }}
		</p>

		<ul>
		{% for step in leg.steps %}
			<li><p>{{ step.html_instructions | raw }}<br><em>({{ step.duration.text }} - {{ step.distance.text }})</em></p></li>
		{% endfor %}
		
	</ul>
	{% endfor %}

{% endfor %}