Earlier this year I wrote an article on 4GuysFromRolla.com showing how to build an ASP.NET WebForms store locator application using Google Maps. Recently, I ported the store locator application to ASP.NET MVC and detailed building the application in Implementing the Store Locator Application Using ASP.NET MVC.
Recently, a reader wrote in and asked what steps would be necessary to include a Directions link with each marker in the map so that, when clicked, the user would see the driving directions from the address they entered and the store of interest. I decided to update the ASP.NET MVC application to include this new feature request. Now, the results page shows a Directions link in both the grid of nearby stores and in the info window that pops up when you click a map marker. Clicking the Directions link opens a new browser window and loads Google Maps, showing the directions from the user-entered address to the selected stores address.
To show the driving directions I send the user to the following URL: http://maps.google.com/maps?f=d&source=s_d&saddr=startingAddress&daddr=destinationAddress.
When the user is sent to the store locator page, the user-entered address (a/k/a, the starting address) is passed through the querystring via a field named Address, so we already know the starting address. But how do we get our hands on the destination address? Recall that view is passed a model that is a collection of NearbyStoreLocation objects; the NearbyStoreLocation class has properties like Address (the street address), City, Region, PostalCode, and so forth. We can build up the address by concatenating these various address parts.
Rather than requiring the view to build up the address, I added a new read-only property to the NearbyStoreLocation class named FormattedAddress, which returns an address Google Maps can parse by piecing together the address-related properties into a string.
public string FormattedAddress
var addrPieces = new List<string>(5);
return string.Join(", ", addrPieces.ToArray());
In the view, the link to the directions can be build like so:
<a target="_blank" href="http://maps.google.com/maps?f=d&source=s_d&saddr=<%=Server.UrlEncode(Request.QueryString["Address"]) %>&daddr=<%=Server.UrlEncode(store.FormattedAddress) %>">Directions</a>
And thats it! Adding the Directions link to the info popup window is a tad more involved because the quotation marks must be escaped using \.
To get your hands on the complete, working code, go to: http://www.4guysfromrolla.com/code/GoogleMapsMVC.zip