I am trying to make a distance calculator using google maps api, and it seems to work some of the time but other times it just blinks.

You can check it out here: http://www.toppagedesign.com/urbanhiker/

The code is this:


Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title>Urban Hiker</title>
      <link href='http://fonts.googleapis.com/css?family=Raleway:400,700' rel='stylesheet' type='text/css'>
      <link rel="stylesheet" href="css/font-awesome.css">
      <link href="styles.css" rel="stylesheet" type="text/css" />
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
      <script type="text/javascript"
         src="https://maps.googleapis.com/maps/api/js?file=api&key=AIzaSyDanRnl4TRZyI5BjvLfWNjtBatjrVwd-LM&sensor=false">
      </script>
   </head>
   <body>
      <?php include("includes/nav.php") ?>
      <div id="latest_news" class="metro">
         <h1><i class="icon-comment"></i> Latest News</h1>
         <div class="scroll">
         <?php
            $number = "1";
            $template = "metro";
            include("news/show_news.php");
         ?>
         </div>
      </div>
      <div id="trip-calc" class="metro">
         <h1><i class="icon-road"></i> Distance</h1>
         <form id="google-api-trip-calc" action="#">
            <span class="emp"><h2>Start</h2></span><input name="address1" type="text" id="address1" />
            <span class="emp"><h2>End</h2></span><input name="address2" type="text" id="address2" />
            <input type="submit" value="Show" onclick="initialize();" />
         </form>
         <div id="distance_direct"></div>
         <div id="map_canvas"></div>
      </div>
      <div id="mission" class="metro">
         <h1><i class="icon-asterisk"></i> Mission</h1>
         <div class="scroll"><p>Ventosus illum vel in modo venio foras turpis occuro
         sed occuro duis. Et quod, utrum importunus praesent
         epulae delenit eum typicus at exerci ullamcorper.
         Paratus cui paulatim pecus capio in veniam quae
         hendrerit vel, iusto adsum blandit epulae. Consequat
         pertineo velit ullamcorper verto, torqueo. Quis lobortis
         tamen olim dolus nobis eu. Sudo obruo imputo euismod
         zelus capto vicis, nisl suscipit suscipit, hos autem
         nisl. Qui conventio voco scisco eros fere vero interdico
         vel vindico valde. Elit ymo et zelus ulciscor quis exerci
         enim delenit. </p>

         <p>Ea ymo aliquip feugait modo refero blandit olim,
         in persto et, facilisi pecus refoveo. Facilisi ibidem
         pala iriure dolus cui qui augue vel iriure. Defui quibus
         nimis letatio wisi capto. </p></div>
      </div>
      <div id="twitter_feed" class="metro">
         <h1><i class="icon-twitter"></i> Twitter Feed</h1>
         <p>Not connected.</p>
      </div>
   </body>
</html>
<script type="text/javascript">
   var location1;
   var location2;
   
   var address1;
   var address2;

   var latlng;
   var geocoder;
   var map;
   
   var distance;
   
   // finds the coordinates for the two locations and calls the showMap() function
   function initialize()
   {
      geocoder = new google.maps.Geocoder(); // creating a new geocode object
      
      // getting the two address values
      address1 = document.getElementById("address1").value;
      address2 = document.getElementById("address2").value;
      
      // finding out the coordinates
      if (geocoder)
      {
         geocoder.geocode( { 'address': address1}, function(results, status)
         {
            if (status == google.maps.GeocoderStatus.OK)
            {
               //location of first address (latitude + longitude)
               location1 = results[0].geometry.location;
            } else
            {
               alert("Geocode was not successful for the following reason: " + status);
            }
         });
         geocoder.geocode( { 'address': address2}, function(results, status)
         {
            if (status == google.maps.GeocoderStatus.OK)
            {
               //location of second address (latitude + longitude)
               location2 = results[0].geometry.location;
               // calling the showMap() function to create and show the map
               showMap();
            } else
            {
               alert("Geocode was not successful for the following reason: " + status);
            }
         });
      }
   }
      
   // creates and shows the map
   function showMap()
   {
      // center of the map (compute the mean value between the two locations)
      latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);
      
      // set map options
         // set zoom level
         // set center
         // map type
      var mapOptions =
      {
         zoom: 1,
         center: latlng,
         mapTypeId: google.maps.MapTypeId.HYBRID
      };
      
      // create a new map object
         // set the div id where it will be shown
         // set the map options
      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
      

      
      // show a line between the two points
      var line = new google.maps.Polyline({
         map: map,
         path: [location1, location2],
         strokeWeight: 7,
         strokeOpacity: 0.8,
         strokeColor: "#FFAA00"
      });
      
      // create the markers for the two locations      
      var marker1 = new google.maps.Marker({
         map: map,
         position: location1,
         title: "First location"
      });
      var marker2 = new google.maps.Marker({
         map: map,
         position: location2,
         title: "Second location"
      });
      
      // create the text to be shown in the infowindows
      var text1 = '<div id="content">'+
            '<h1 id="firstHeading">First location</h1>'+
            '<div id="bodyContent">'+
            '<p>Coordinates: '+location1+'</p>'+
            '<p>Address: '+address1+'</p>'+
            '</div>'+
            '</div>';
            
      var text2 = '<div id="content">'+
         '<h1 id="firstHeading">Second location</h1>'+
         '<div id="bodyContent">'+
         '<p>Coordinates: '+location2+'</p>'+
         '<p>Address: '+address2+'</p>'+
         '</div>'+
         '</div>';
      
      // create info boxes for the two markers
      var infowindow1 = new google.maps.InfoWindow({
         content: text1
      });
      var infowindow2 = new google.maps.InfoWindow({
         content: text2
      });

      // add action events so the info windows will be shown when the marker is clicked
      google.maps.event.addListener(marker1, 'click', function() {
         infowindow1.open(map,marker1);
      });
      google.maps.event.addListener(marker2, 'click', function() {
         infowindow2.open(map,marker1);
      });
      
      // compute distance between the two points
      var R = 6371;
      var dLat = toRad(location2.lat()-location1.lat());
      var dLon = toRad(location2.lng()-location1.lng());
      
      var dLat1 = toRad(location1.lat());
      var dLat2 = toRad(location2.lat());
      
      var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(dLat1) * Math.cos(dLat1) *
            Math.sin(dLon/2) * Math.sin(dLon/2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      var d = R * c;
      var d = Math.floor(d);
      
      document.getElementById("distance_direct").innerHTML = "<br/><span class='emp'>Distance: "+d+" mi.</span>";
   }
   
   function toRad(deg)
   {
      return deg * Math.PI/180;
   }
</script>


Can you guys see any problems with it?

EDIT:

Right after posting i found out the problem is this line:


Code:

<form id="google-api-trip-calc" action="#">


I just removed the action="#" part and it worked. Smile

Don't know if I should leave this post or delete it...

EDIT2: woops, still doesn't work. Please help... Smile
Depending on which browser you are using, it can help you pinpoint your issue. For example when using Firefox if you click Tools>Web Developer>Error Console, it will show all warnings and errors generated.
The only error i get is something about on() being deprecated and I should use self.on().
I don't see anything wrong off the top of my head. Please do check the Javascript error console carefully after you try to run a calculation or two and see what happens. You say it only works some of the time: can you find a commonality between the times when it works and the times when it doesn't?
Well, here's what I'm getting after a couple tries:


Code:

Timestamp: 11/08/2012 10:28:55 AM
Error: [Exception... "'JavaScript component does not have a method named: "handleEvent"' when calling method: [nsIDOMEventListener::handleEvent]"  nsresult: "0x80570030 (NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED)"  location: "<unknown>"  data: no]


EDIT:

fixed it by changing the form to a div and the submit button to a normal button.
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement