Solved

Distance calculator using Google Maps API

Posted on 2012-03-09
4
1,019 Views
Last Modified: 2012-03-22
Please let me know how I can calculate the walking and driving distances using Google Maps API.

If possible, please provide some sample code. Thanks!
0
Comment
Question by:dshrenik
  • 3
4 Comments
 
LVL 13

Expert Comment

by:Molnar István
ID: 37704444
here is the code i used to calculate the distance from two addresses
in <head></head> put this code:
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=PASTE_API_KEY" type="text/javascript"></script>
       <script language="javascript" type="text/javascript">
     var map = null;
    var geocoder = null;
    var marker1=null;
    var marker2=null;
    var marker1_lat=null;
    var marker2_lat=null;
     var marker1_lon=null;
    var marker2_lon=null;
    var polyline=null;
    function load() 
    {
      if (GBrowserIsCompatible()) 
      {
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(47.4984056, 19.0407578), 13);
        map.setUIToDefault();
        map.addControl(new GOverviewMapControl());
        geocoder = new GClientGeocoder();
      }
    }
    function GeoKodolo(address1,address2) 
    {
    map.clearOverlays();
    polyline=null;
      if (geocoder) 
      {
      //address1
        geocoder.getLatLng
        (
          address1,
          function(point) 
          {
            if (!point) 
            {
              alert("Not found: "+address1+"'");
            } 
            else 
            {
              marker1 = new GMarker(point);
              map.addOverlay(marker1);
              marker1_lat=marker1.getPoint().lat();
              marker1_lon=marker1.getPoint().lng();           
            }
          }
        );
       //address2
       geocoder.getLatLng
        (
          address2,
          function(point) 
          {
            if (!point) 
            {
              alert("Not found: "+address2+" '");
            } 
            else 
            {
              marker2 = new GMarker(point);
              map.addOverlay(marker2);
             marker2_lat=marker2.getPoint().lat();
              marker2_lon=marker2.getPoint().lng();
            }
          }
        ); 
      var polyOptions = {geodesic:true};
      polyline = new GPolyline([
      new GLatLng(marker1_lat, marker1_lon),
      new GLatLng(marker2_lat, marker2_lon)
    ], "#ff0000", 10, 1, polyOptions);
       var mark1=new GLatLng(marker1_lat, marker1_lon);
       var mark2=new GLatLng(marker2_lat, marker2_lon);
       var dist=document.getElementById("dist_lbl");
       dist.innerHTML="Distance"+address1+" and "+address2+" is: "+distance(marker1_lat,marker1_lon,marker2_lat,marker2_lon,"K").toFixed(0)+" Km";    
    map.addOverlay(polyline);
    map.setCenter(polyline,10);
      }//ifend

    }//fugg end
    function distance(lat1, lon1, lat2, lon2, unit) //the funtion that calculates the distance
    {
		var theta = lon1 - lon2;
		var dist = Math.sin(Deg2Rad(lat1)) * Math.sin(Deg2Rad(lat2)) + 
						Math.cos(Deg2Rad(lat1)) * Math.cos(Deg2Rad(lat2)) * Math.cos(Deg2Rad(theta));
		if (dist > 1.0)
			dist=1.0;
		dist = Math.acos(dist);
		dist = Rad2Deg(dist);
		var result = dist * 60 * 1.1515;
		switch (unit.toUpperCase())
		{
			case "M": //mile
				return result;
			break;
			case "K"://km
				return result * 1.609344;
			break;
			case "N"://nautic mile
				return result * 0.8684;
			break;
			default:
				return result * 1.609344;
			break;
		}
    }
 
    function Deg2Rad(deg)
    {
		return deg * Math.PI / 180;
    }
    
    function Rad2Deg(rad)
    {
		 return rad * 180 / Math.PI;
    }
 
</script>    

Open in new window

in <body></body> put this code:
<center>
			<input type="text" name="address1" id="addr1" value="Budapest, Hungary" style="width: 180px" />
                <input type="text" name="addres2" id="addr2" value="Szeged, Hungary" style="width: 180px; position: static" />
	<a onclick="GeoKodolo(document.getElementById('addr1').value,document.getElementById('addr2').value)"><img alt="[show]" src="img/web_find.png" style="vertical-align: middle; cursor: pointer;" title="[show]" /></a>
                <br/>	
                <div id="dist_lbl"></div>
            </center>		
            <br/>
		    <div id="map" style="width: 620px; height: 400px"></div> 

Open in new window



hope it helps
0
 
LVL 13

Expert Comment

by:Molnar István
ID: 37704446
oh, and i forgot that you must add the following code to initialize the map:
<body onload="load()" onunload="GUnload()">
0
 

Author Comment

by:dshrenik
ID: 37739158
I am having trouble integrating all the pieces. If possible, could you please combine everything into 1 file? Thanks!
0
 
LVL 13

Accepted Solution

by:
Molnar István earned 500 total points
ID: 37753882
here is the entire file
i created a button to search and a select to change the driving type

hope it helps
driving4.html
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Envision that you are chipping away at another e-business site with a team of pundit developers and designers. Everything seems, by all accounts, to be going easily.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now