How to Have Phone Read Turn by Turn Directions for a Preplanned Route

Read Fourth dimension: 16 mins Languages:

In this tutorial, nosotros volition go through the process of creating a pocket-size widget that allows users to retrieve turn-by-turn directions to a specified location. We'll be using the Google Maps API, via JavaScript, to provide this rather advanced functionality.

Final Product Final Product Final Product

Getting An API Key

The only caveat with using Google Maps is we must employ for an API central, but this is a fairly trivial process if yous already take a Google/GMail account. Unfortunately due to the requirements of Google we must develop on the domain that we provide Google, i.e. we can not develop on a local server. Fortunately for united states the process volition be quick and nosotros won't spend a lot of time on the live server. As well, be certain to store you API cardinal in a prophylactic place because I could not detect a manner to call back them one time generated, though I guess you could just recreate i.

The Country of Affairs

Earlier we dive into code allow me discuss the reason backside this idea. Every bit near developers I spend a lot of time on the spider web. One item subset of websites I visit are local businesses who certainly don't have great resources to devote to web design, but hopefully the people that are developing those sites will run into articles similar this and realize how easy it is to include a full-featured map into whatever webpage. Virtually any website representing a modest business organization has a folio dedicated to telling users how to locate their physical location. Frequently times you go a map with their location pinned on it, which doesn't help users who don't know the area. In this tutorial we are going to change that and permit users enter their address and get plow-past-plough directions to whatever address we want.

Including the Google Maps Javascript Library

Now that the soapbox is out of fashion lets look into code. The first thing we demand to practise is include the Javascript library that contains all the Google Maps methods. Google probably generated this code when y'all created your API key, but that might have pointed to the version 3 API which is still in beta testing. Here is the link to the API version 2 be sure to insert your API key. We are too going to include a file, awarding.js that will hold our custom functions, I stored mine in a directory at the root level called js. The following code goes within the head department of your page.

The HTML Code

In the body section of our folio nosotros demand some limited markup. I will briefly become over the required $.25, and you lot can look at the source code to see the fluff I included in my demo. The showtime chemical element is an empty div with an ID of map_canvas, this is the placeholder that we indicate the Google Maps calls to and it will generate all the map markup within that chemical element.

Next I created a div to hold the organization address and the course for the user to enter their address. You tin look over this code but it is pretty simple and not very hard to discern information technology'southward meeting. Be sure to look at my CSS to see how it is styled in my demo.

Notice that nosotros are submitting this page to itself this is then we tin can process the folio using PHP if the user has JS disabled. If they have JS enabled nosotros desire to execute a function, overlayDirections() which we will take a look at a little later on. The bulk of this code goes to the select box that lets the user selection their state, I've condensed it for the sake of those press this article, only you tin can grab the full code from the download. Other interesting notes is we gear up the size and maxlength of the zip code text field to v. The final matter to take note is that nosotros take assigned ids and names to all of the form elements.

Bootstrapping and Declaring Variables

Alright now we tin can move into the meat of this tutorial, the JavaScript code. Nearly all the calls we are going to make come from the Google Maps API that nosotros referenced earlier. Google provides excellent documentation and instance code on their website so be certain to check information technology out. I'll attempt to link to relevant pages as I utilize them.

The offset thing is while we accept our HTML page open lets bootstrap the initialize function by setting onload attribute. Note: this could exist done in jQuery using the $(certificate).set() office.

Now we are going to motion in to the js/appication.js file. The very first thing we need to do is set some variables. Some lawmaking evangelist will probably hunt me downwards for declaring global variables, simply I believe in this case we should be okay. I'll give yous the code and and so explicate how we volition use each one.

  • gdir: holds the GDirections object used to obtain driving directions results and display them on a map and/or a text panel.
  • fromAddress: a cord that holds the full address of the user.
  • toAddress: a string that holds the business organization/organization address

The initialize() Function

The initialize() office we chosen earlier will exist used to create the Map on the page and place a custom marking of our location.

The first thing we need to do is check if the browser is compatible with Google Maps, and for this Google provides the GBrowserIsCompatible() in their API. In essence it returns true if the browser is compatible and allows us to move into the rest of our function. I decided to abstruse some of the values to variables at the top of the role so that this could easily be ported to many applications.

The companyMarkerImage is a string of the location of a pocket-sized image we will place at our location on the map. This is something I think is a squeamish touch to have a custom icon to stand for your business which volition personalize the generic Google Map view. Next, companyLatLng holds a GLatLng object corresponding to a latitude, longitude bespeak in the globe. Don't run out and purchase a GPS device to get these numbers we tin can employ maps.google.com . In the search box type your address and when information technology finds the location click the Link button on the top right of the map. Scroll through the first text box in the modal window and find &sll=....

You lot can copy and paste those coordinates into the parameters of our GLatLng constructor. This is the point on the map where nosotros volition place our custom image. The next variable, companyMarkerSize, holds a GSize object which represents the width and height of your custom mark image. Next nosotros set toAddress which is the address of the concern. The final variable, defaultZoomLevel, simply tells the map what you want the default zoom level to exist ranging from 1 to 18.

The next line of code creates a GMap2 object. Google describes this equally "the primal class in the API." This loads the map information and allows us to manipulate what is shown in the map surface area. It takes one argument a DOM object pointing to the chemical element containing the map, #map_canvas. Adjacent we set gdir to concord the GDirections object. This is the interface we use to query Google Maps for directions. The constructor takes two arguments a map object and a DOM object where we desire to put the turn-by-plow directions. I cull to create an empty div beneath #addresses called #directions.

When using spider web services we always run the risk of getting an error returned. Nosotros can make this as pain free as possible using the GEvent course. In this bit of code we are saying that if we have an error getting the directions to execute a custom callback role, handleErrors in our case. We straight telephone call the addListener() function which registers a callback. Information technology takes 3 arguments a source object, a string referring to the blazon of effect we want to execute the callback on, and a handler which points to a function nosotros want executed. The office, handleErrors, is something we will look at later.

The concluding few lines in initialize() are used to create our custom marker, I chose a Jayhawk found on KU'southward homepage. createMarker is a wrapper function I wrote to abstract the lawmaking required to create a custom marking. Information technology takes three arguments: a reference to a GLatLng object where we want to place the image on the, a cord respresenting the path to an paradigm, and a reference to a GSize object that represents the size of the epitome. Next we use the setCenter() method of the GMap2 form which takes two arguments a GLatLng object of the coordinates to centre on, and an integer for the zoom level. Notice we are passing in the variables nosotros set in the settings block at the top of the initialize() function. The final line of code uses the addOverlay() method. This is what actually adds the custom image to the map.

The initialize() function does a lot of heavy lifting, but it certainly can show for it. Afterwards we write the createMarker() function next you will be able to load up the awarding and run across some progress. Just first lets recap the initialize() function.

The createMarker() Function

Adjacent nosotros will create a wrapper function that takes all the hurting out of creating a marker with a custom epitome. The reason I cull to abstruse this is because it is an involved process and would ataxia upwardly our initialize() function even more. Another added do good is that we can add multiple markers very quickly without repeating a lot of code.

Considerably smaller than our get-go function, but only as important. First we declare a new variable, marker, and store a GIcon object. It tin can take two arguments copy which is a GIcon object that information technology will copy backdrop from, and image which is a string representing a path to a custom image. G_DEFAULT_ICON is a constant that represents a default marker, and the imageURL comes from the settings block in initialize(). We only have to set one more than holding, iconSize which is of blazon GSize, this represents the size of our custom image and likewise comes from the settings block. The final line of code returns a GMarker object which takes two arguments latlng, and icon. The first, latlng is a reference to the GLatLng object nosotros alleged in the settings cake. The side by side argument is for the GIcon object nosotros simply created. That is all we need to exercise for the map portion of our application to piece of work. You can now load upward the folio and come across how like shooting fish in a barrel information technology is to go a nice map on our website.

Adding Directions

This is past far my favorite part about this tutorial, allowing users to enter an address and receive back a map with the route highlighted and turn-past-plough directions. Through the use of this API we can condense something that would require thousands of lines of lawmaking and an incredible amount of processing resource to merely a handful of code.

The get-go line I have actually extended into five lines for clarity. In essence this grabs all the values from the form and puts a space between each part. I thought this was meliorate than asking the user to enter the whole address into a single text box considering that tin become confusing.

The second line makes use of the gdir we set up in initialize(). Nosotros phone call the load() method and pass a unmarried string argument, which is essentially what nosotros would pass maps.google.com via the search box. The from: and to: keywords assist tell Google which address needs to be the starting point and which needs to be the catastrophe indicate. That is all we demand to do for directions, yeah I was shocked too! If yous visit your page again you can come across this in activeness.

Handling Errors

Next we are going to declare the handleErrors() office. I grabbed this from Google Sample code on their API website. I won't get into any detail because it fairly straightforward.

It has a long if...elseif...else statement that checks for many fault types and alerts the user if any occur. Y'all can change this if you wish to brand the alert less technical.

Degradable

Equally practiced spider web developers nosotros should make certain our website works for every bit many users as possible, including those with JavaScript disabled. In this state of affairs I chose to redirect those with JS disabled to Google Maps with the search performed then they all the same get directions. This is done using PHP to evaluate the class and redirect to Google Maps. At the top of your HTML folio insert this code:

First we have a settings cake again which only has one variable to ready, $TO. This is similar to what nosotros did in JavaScript for toAddress, only we need the same string in PHP too. Next we have an if statement to cheque for POSTed data which means our course was submitted. Now we grab the form values and place them in a cord with spaces and store that in a variable, $FROM. Then nosotros store the language value to $LOC, more on this later on. The $url variable will agree the cord representing the query URL to Google. Notice that we url-encode our values so they safely travel on the redirect. The final line of code uses PHP headers to redirect the user to Google.

Optional: Add Multi-Language Support

As a business you want to reach out to as many people as possible and part of that process is supporting multiple languages. In Google Maps supporting other languages comes at no extra cost to united states.

Beginning open up your HTML folio and insert the following lawmaking between your form tags.

Of course if you want to remove any languages just delete the choice tag for it, yous can also modify the default by moving the selected attribute.

Moving to js/application.js, we need to brand just ii changes. Starting in the overlayDirections() function afterward nosotros create the string fromAddress add this to grab the selected value from the language select box and save information technology to our linguistic communication variable.

Next, add an argument to the gdir.load() function, this takes an options set. In our case we only need to declare locale so it knows the proper language and units for the turn-by-turn directions.

Annotation: Nosotros already included this in the PHP redirect and if you want to disable this just statically prepare $LOC.

Decision

That is all we need for this amazing feature, and I hope y'all learned a bit about Google Maps forth the way. I challenge you as developers to proceed to find interesting ways to integrate maps in to your applications. Anytime a model is location enlightened, y'all should question if your project has a use for visual representation on a map. Thanks for reading; as always, I am here to help in the comments or on Twitter (@noahhendrix).

  • Follow usa on Twitter, or subscribe to the NETTUTS RSS Feed for more daily spider web development tuts and manufactures.

stallingsloord1997.blogspot.com

Source: https://code.tutsplus.com/tutorials/turn-by-turn-directions-with-the-google-maps-api--net-5620

0 Response to "How to Have Phone Read Turn by Turn Directions for a Preplanned Route"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel