Solved

Distance calculator using Google Maps API

Posted on 2012-03-09
4
1,029 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

I've been asked to discuss some of the UX activities that I'm using with my team. Here I will share some details about how we approach UX projects.
Does your audience prefer people in photos or no people? How can you best highlight what you’re selling? What are your competitors doing, and what can you do that is different and unique from them?  Continue reading to learn how to make your images …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

770 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