Thursday 30 June 2011

Generate Directions Using Google Maps Javascript API

A sample project for this can be found here...

It's common on the web, to want to explain exactly where your office, shop or restaurant is, and there are different ways you can do this, you could simply stick your address on a contact us page, and let potential customers find your location for themselves, or you could get the details on the google maps site and create a link to the generated google url on your site, or could could even display a map image to give a customer an idea where you are hiding!

I was recently asked come up with a solution allow customers to be able to not only easily view my company's location on an interactive map, but also be able to input their own location, only for the web site to give directions, a summary of distance and time and also an updated route map. This solution would need to solve the problems generated by the alternative methods I mentioned:

  • Users would not be directed away from the site (or even page) to get information about the journey.
  • Users would be able to get exact information about their journey, not just your location.
  • It is essential to give the users a good experience, if the correct information tailored to them is available with a couple of keypresses and the click of a mouse button, there is more chance of them being impressed and maybe just turning up at your store.
Google's Javascript API fits the bill perfectly for this, there is loads of documentation out there on how to use it, but since I have cobbled the base of the code altogether into a little R&D project, thought it would be a good thing to share, as I struggled to find a sample project I could download and have a look at.

The project itself is done in MVC3 using Razor, the reasoning behind this I needed to go one step further and determine the the nearest store to the users postcode, I achieved this with a jQuery request to the server that handled the request and returned the nearest site's postcode, ready for me to port into my actual site, it's not relavent to this post so it's not included in this post, but it's pretty straight forward...

The bones of this small project is purely Html and javascript/Jquery so feel free to import into your own project. The UI is basically a origin text box, destination text box, and a map place holder...

The sample code can be found here...

One more note...
The Google API adds some styles to the map place holder that initially will make the page look a bit odd ,so have a look in the CSS for how I got round this at the bottom of the site.css, you can then extend on this to get it exactly how you want it for your own site.

Please let me know your thoughts and comments

Thanks
Jason

No comments: