Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Distance calculator using Google Maps API

Posted on 2012-03-09
4
Medium Priority
?
1,062 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 2000 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

Understanding Web Applications

Without even knowing it, most of us are using web applications on a daily basis. Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We often confuse these web applications tools for websites.  So, what is the difference?

Question has a verified solution.

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

When it comes to write a Context Sensitive Help (an online help that is obtained from a specific point in state of software to provide help with that state) ,  first we need to make the file that contains all topics, which are given exclusive IDs. …
This article discusses how to implement server side field validation and display customized error messages to the client.
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…
This video teaches users how to migrate an existing Wordpress website to a new domain.
Suggested Courses

636 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