Skip to main content

Drive along - Cool coding

         This is something that will demonstrate to you the power of mapping! This is a Google Maps API v2 example, but just copy and paste the code in an html file and you will see something very cool! This will prove that mapping is real fun!

         Let's have a look at the code first. Copy this code in your html file. Don't worry about the length of the code and the post in general. Just execute the code and you will surely enjoy what you see!

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>
Drive Along
</title>

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAu3HXU_hLdVPTFGqLed_FCxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQbblEPYBGNoRsuuSU9aBfSq4VAZA" type="text/javascript">
</script>

<script src="http://econym.org.uk/gmap/epoly.js" type="text/javascript">
</script>

</head>

<body onunload="GUnload()">

<div id="controls">
<form onsubmit="start();return false" action="#">
Enter start and end addresses.<br />
<input type="text" size="80" maxlength="200" id="startpoint" value=" " />
<br />
<input type="text" size="80" maxlength="200" id="endpoint" value=" " />
<br />
<input type="submit" value="Start"  />
</form>
</div>

<div id="map" style="width: 700px; height: 500px">
</div>
<div id="step">&nbsp;
</div>
<div id="distance">Miles: 0.00
</div>

<script type="text/javascript">
if (GBrowserIsCompatible())
{
    var map = new GMap2(document.getElementById("map"));
          map.addControl(new GMapTypeControl());
          map.setCenter(new GLatLng(0,0),2);
          var dirn = new GDirections();
          var step = 5; // metres
          var tick = 100; // milliseconds
          var poly;
          var eol;
          var car = new GIcon();
        car.image="http://www.freeiconsweb.com/Freeicons/Car_icon/Dodge%20Viper%20SRT-10.png"
        car.iconSize=new GSize(28,28);
        car.iconAnchor=new GPoint(16,9);
          var marker;
          var k=0;
          var stepnum=0;
          var speed = "";  

          function animate(d)
    {
            if (d>eol)
        {
                  document.getElementById("step").innerHTML = "<b>Trip completed<\/b>";
                  document.getElementById("distance").innerHTML =  "Miles: "+(d/1609.344).toFixed(2);
                  return;
            }
            var p = poly.GetPointAtDistance(d);
            if (k++>=180/step)
        {
                  map.panTo(p);
                  k=0;
            }
            marker.setPoint(p);
            document.getElementById("distance").innerHTML =  "Miles: "+(d/1609.344).toFixed(2)+speed;
            if (stepnum+1 < dirn.getRoute(0).getNumSteps())
        {
                  if (dirn.getRoute(0).getStep(stepnum).getPolylineIndex() < poly.GetIndexAtDistance(d))
            {
                        stepnum++;
                        var steptext = dirn.getRoute(0).getStep(stepnum).getDescriptionHtml();
                        document.getElementById("step").innerHTML = "<b>Next:<\/b> "+steptext;
                        var stepdist = dirn.getRoute(0).getStep(stepnum-1).getDistance().meters;
                        var steptime = dirn.getRoute(0).getStep(stepnum-1).getDuration().seconds;
                        var stepspeed = ((stepdist/steptime) * 2.24).toFixed(0);
                        step = stepspeed/2.5;
                        speed = "<br>Current speed: " + stepspeed +" mph";
                  }
            }
        else
        {
                  if (dirn.getRoute(0).getStep(stepnum).getPolylineIndex() < poly.GetIndexAtDistance(d))
            {
                        document.getElementById("step").innerHTML = "<b>Next: Arrive at your destination<\/b>";
                  }
            }
            setTimeout("animate("+(d+step)+")", tick);
          }

    GEvent.addListener(dirn,"load", function()
    {
        document.getElementById("controls").style.display="none";
            poly=dirn.getPolyline();
            eol=poly.Distance();
            map.setCenter(poly.getVertex(0),17);
            map.addOverlay(new GMarker(poly.getVertex(0),G_START_ICON));
            map.addOverlay(new GMarker(poly.getVertex(poly.getVertexCount()-1),G_END_ICON));
            marker = new GMarker(poly.getVertex(0),{icon:car});
            map.addOverlay(marker);
            var steptext = dirn.getRoute(0).getStep(stepnum).getDescriptionHtml();
            document.getElementById("step").innerHTML = steptext;
            setTimeout("animate(0)",2000);  // Allow time for the initial map display
          });

          GEvent.addListener(dirn,"error", function()
    {
            alert("Location(s) not recognised. Code: "+dirn.getStatus().code);
          });

          function start()
    {
            var startpoint = document.getElementById("startpoint").value;
            var endpoint = document.getElementById("endpoint").value;
            dirn.loadFromWaypoints([startpoint,endpoint],{getPolyline:true,getSteps:true});
          }

}
</script>
</body>
</html>


         Please execute the above code and please drop in your comments about what you think about it. You can also drop me a mail about your feedbacks about this code or the blog in general!

Comments

  1. Very nice code! Thank you for sharing it =)

    ReplyDelete
  2. Shreerang it is really a nice and cool post. Thanks , I am learning a lot from your blog.Keep posting..

    ReplyDelete
  3. what is the format for writing the coordinates in the boxes, as its not working either by dms or dc formats

    ReplyDelete
    Replies
    1. Co-ordinates should be in degree-decimal format or you can directly enter the addresses also.

      Delete

Post a Comment

Please leave your comments here...

Recommended for You

Where does Google get it's live traffic data from?

Referring to a post that I wrote earlier, Google’s - Live traffic Layer , ever wondered how Google collected this data? I was wondering the other day, how Google received live data to display it on their maps as a layer! I looked up the web and found something very interesting and am sharing the same with you all. As we all know, the traffic layer is available most accurately in several states in USA. Most major metro areas in the US have sensors embedded in their highways. These sensors track real time traffic data. Easy to miss at high speeds (hopefully anyway, traffic permitting), more commonly noticed may be the similar sensors that often exist at many busy intersections that help the traffic lights most efficiently let the most amount of people through. The information from these tracking sensors is reported back to the Department of Transportation (DOT). The DOT uses this data to update some of the digital signs that report traffic conditions in many metro areas. They als...

Two maps on the same page - Side-by-side

    How good I am feeling to post a code example after such a long time! It's been all "news" over the past so many posts! Well now that I am finally doing a code example, I am posting a very highly requested code sample. Placing two Google Maps on the same page (Now that's simple you would say!), but side by side. Now this is the thing that most people struggle with. Well, implementing the second part is also very simple, as you will see in today's code.     Let's see the code. Here it is!     The output of the above code will be as seen in the result section above.     As most of you will realize, there are two maps, one centered at "Pune" and other at "Noida". Why I chose these two locations? Well, just like that!...The main issue of concern is how the maps appeared side-by-side and not one below the other as would be normal behavior of two "div" elements used in the same page. Now here is the trick! Check out the...

Playing with the markers and info window bubbles...

    In the last few posts, we have seen some marker examples and some information window examples. Now, lets do something interesting combining these two things. Just writing that "This is an info window" in the information bubble is not very interesting! And I know this...Have gone through the same phase!     So, today we will do something interesting! We will display the latitude- longitude co-ordinates of the point that the user clicks on the map! Doing this is not at all complex! Copy paste the following code and you will see for yourself a map coming to life!     The output of the above code looks as seen in the result section above! If you have any queries regarding the above code please comment on the blog post or feel free to contact me at my mail ID .

Form info window

         Today we will look at a Google Maps API v3 example to add a form in the information bubble! This is usually required when we wish to accept some data/information from the user! This data can be saved to a server in the form of an XML file or a database! The information can then be retrieved back at a later stage, when necessary!          In this example we will only look at form in the information bubble! The connectivity part with the server will be discussed in another post! So, today's code snippet is as seen below! <html> <head> <title> Google Maps API v3 - Adding marker and info window on Click and creating a form in the infowindow with the lat-lng information in it. </title> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> var map;    //When using ev...

Retriving co-ordinates...

         We have seen 2 Google Maps API v3 examples wherein we have retrieved the latitude-longitude co-ordinates of the point of click on the map. In the first example we have displayed the co-ordinates in the information window and in the second , we have displayed the co-ordinates in a form in the information window.         Today we will create a code to retrieve the latitude longitude co-ordinates in a text box while simultaneously a marker appears on the map as well. So, here goes the code. <html> <head> <title> Google Maps API v3 - Adding marker on Click and retrieving the co-ordinates in a text box </title> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> var map;    //When using event as a parameter to a function declare map, strictly as a global variable fun...