Solved

Distance calculator using Google Maps API

Posted on 2012-03-09
4
1,036 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Get to know the ins and outs of building a web-based ERP system for your enterprise. Development timeline, technology, and costs outlined.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
The is a quite short video tutorial. In this video, I'm going to show you how to create self-host WordPress blog with free hosting service.

749 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