Page 1 of 2 12 LastLast
Results 1 to 10 of 19

Thread: Local Value Lost?

  1. #1
    Join Date
    May 2007
    Location
    Boston,ma
    Posts
    2,127
    Thanks
    173
    Thanked 207 Times in 205 Posts

    Default Local Value Lost?

    I have this code/function which works most of the way through. I thought end, distanceArray, and the timeArray were local and should be accessible throughout the function (correct?) so at line 36 I get the correct output

    alert(distanceArray[a]);
    but at line 46 all the values are undefined. I figure I'm missing something here but am not sure what, this is using googles api but I think it's my JS that is incorrect. If you want to test it out yourself I got the full sample here http://174.120.151.156/~crazychr/test2.html.

    Code:
    function calcRoute() {
    	var new_address = document.getElementById('new_address').value;	
    	// Retrieve the start and end locations and create
    	// a DirectionsRequest using WALKING directions.
    	end[0] = "Ithaca, New York, United States";
    	end[1] = "Fountain Valley, California, US";
    	end[2] = "Los Angeles, California, US";
    	end[3] = "San Francisco, California, US";
    	end[4] = "Huntsville, Alabama, US";
    	end[5] = "Atlanta, Georgia, US";
    	end[6] = "Berlin, Germany";
    	end[7] = "Boston, Massachusetts, US";
    	end[8] = "Chicago, Illinois, us";
    	end[9] = "Columbus, Ohio, US";
    	end[10] = "Detroit, Michigan, us";
    	end[11] = "Des Moines, Iowa, US";
    	end[12] = "London, England";
    	for (var a = 0; a < end.length; a++) {
    		var request = {
    			origin: new_address,
         		destination: end[a],
         		travelMode: google.maps.DirectionsTravelMode.DRIVING
    		};
    		// Route the directions and pass the response to a
    		// function to create markers for each step.
    		directionsService.route(request, function(response, status) {
    			//	if (status == google.maps.DirectionsStatus.OK) {
    				//       var warnings = document.getElementById("warnings_panel");
    				//	    warnings.innerHTML = "<b>" + response.routes[0].warnings + "</b>";
    				//        directionsDisplay.setDirections(response);
    				//        showSteps(response);
    			//  }
    			if (response.status == "OK") {
    				distanceArray[a] = (response.routes[0].legs[0].duration.value * .000621371192) + " Miles";
    				TimeArray[a] = response.routes[0].legs[0].duration.text;
    				alert(distanceArray[a]);
    			} else {
    				//	alert("Error with Request.");
    				distanceArray[a] = 9999999;
    				TimeArray[a] = "Never";
    			}
    		});
    	}
    	//distanceArray.sort(function(a,b){return a - b})
    	for (var m = 0; m < 12; m++) {
    		document.getElementById("output").innerHTML += "<br />\n" + m + ". " + distanceArray[m];
    	}
    }
    Last edited by bluewalrus; 12-17-2010 at 08:14 PM.
    Corrections to my coding/thoughts welcome.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Hmm, I've looked at this some more. On the live page you have these arrays defined in the global scope, so your question was misleading. This seems to work, but you gotta click twice, change:

    Code:
    	for (var m = 0; m < 12; m++) {
    		document.getElementById("output").innerHTML += "<br />\n" + m + ". " + distanceArray[m];
    	}
    to:

    Code:
    	for (var m = 0; m < distanceArray.length; m++) {
    		if (distanceArray[m]){
    			document.getElementById("output").innerHTML += "<br />\n" + m + ". " + distanceArray[m];
    		}
    	}
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Gnaw we're getting somewhere:

    Code:
    <!DOCTYPE html>
    <html>
      <head>
    <title>Google Maps JavaScript API v3 Example: Event Closure</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <!-- <link rel="stylesheet" type="text/css" media="screen" href="videomap.css" />
    -->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    var map, directionDisplay, directionsService, stepDisplay, markerArray = [], distanceArray = [], TimeArray = [], end = [];
    	end[0] = "Ithaca, New York, United States";
    	end[1] = "Fountain Valley, California, US";
    	end[2] = "Los Angeles, California, US";
    	end[3] = "San Francisco, California, US";
    	end[4] = "Huntsville, Alabama, US";
    	end[5] = "Atlanta, Georgia, US";
    	end[6] = "Berlin, Germany";
    	end[7] = "Boston, Massachusetts, US";
    	end[8] = "Chicago, Illinois, us";
    	end[9] = "Columbus, Ohio, US";
    	end[10] = "Detroit, Michigan, us";
    	end[11] = "Des Moines, Iowa, US";
    function initialize() {
    	var myOptions = {
    		zoom: 10,
    		center: new google.maps.LatLng(0, 0),
    		mapTypeId: google.maps.MapTypeId.ROADMAP
      	}
    	var map = new google.maps.Map(
    	document.getElementById("map_canvas"), myOptions);
    	setMarkers(map, videographer);
    	directionsService = new google.maps.DirectionsService();
    	var rendererOptions = {
          map: map
        }
        directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)    
        // Instantiate an info window to hold step text.
        stepDisplay = new google.maps.InfoWindow();
        var opt = document.createElement('option'), topt;
        for(var i = 0; i < end.length; ++i){
        	topt = opt.cloneNode(false);
        	topt.value = end[i];
        	topt.appendChild(document.createTextNode(end[i]));
        	document.getElementById('new_address').appendChild(topt);
        }
    }
    	var videographer = [ 
    	['One', 42.4433333, -76.5, 1],
    ['Two', 33.7091847, -117.9536697, 2],
    ['Three', 34.0522342, -118.2436849, 3],
    ['FOur', 37.7749295, -122.4194155, 4],
    ['Five', 34.7303688, -86.5861037, 5],
    ['Six', 33.7489954, -84.3879824, 6],
    ['Seven', 52.5234051, 13.4113999, 7],
    ['eight', 42.3584308, -71.0597732, 8],
    ['Nine', 41.850033, -87.6500523, 9],
    ['ten', 39.9611755, -82.9987942, 10],
    ['eleven', 42.331427, -83.0457538, 11],
    ['twelve', 41.6005448, -93.6091064, 12]
    	];
    function setMarkers(map, locations) {
    	var bounds = new google.maps.LatLngBounds();
    	for (var i = 0; i < locations.length; i++) {
    		var videographer = locations[i], myLatLng = new google.maps.LatLng(videographer[1], videographer[2]), marker = new google.maps.Marker({
    		position: myLatLng,
    		map: map,
    		title: videographer[0]
    		});
    	    bounds.extend(myLatLng);
    	    map.fitBounds(bounds);
    	}
    }
    function calcRoute(a) {
    	var request = {
    		origin: document.getElementById('new_address').value,
    		destination: end[a],
    		travelMode: google.maps.DirectionsTravelMode.DRIVING
    	}, output = document.getElementById('output'), r = '';
    	if(a === 0){
    		output.innerHTML = '&nbsp;';
    	}
    	directionsService.route(request, function(response, status){
    		if (response.status === 'OK'){
    			distanceArray[a] = (response.routes[0].legs[0].duration.value * .000621371192) + ' Miles';
    			TimeArray[a] = response.routes[0].legs[0].duration.text;
    		} else {
    			distanceArray[a] = 9999999;
    			TimeArray[a] = 'Never';
    		}
    		if(++a < end.length){
    			calcRoute(a);
    		} else {
    			for (a = 0; a < distanceArray.length; ++a) {
    				if (distanceArray[a]){
    					r += (a? '<br />\n' : '') + a + '. ' + distanceArray[a];
    				}
    			}
    			output.innerHTML = r;
    		}
    	});
    }
    function showSteps(directionResult) {
        // For each step, place a marker, and add the text to the marker's
        // info window. Also attach the marker to an array so we
        // can keep track of it and remove it when calculating new
        // routes.
    	var myRoute = directionResult.routes[0].legs[0];
    	for (var i = 0; i < myRoute.steps.length; i++) {
    		var marker = new google.maps.Marker({
    		position: myRoute.steps[i].start_point, 
    		map: map
    	});
    	markerArray[i] = marker;
    	}
    }
    </script>
    </head>
    <body onload="initialize()">
    <div id="form" style="width:300px; float:left; height:50px;">
    <select name="new_address" id="new_address"></select>
    <input type="Submit" value="Find Videographer" onclick="calcRoute(0)" />
    </div>
    <div id="output" style="background:#FF0000; width:200px; float:left;">&nbsp;</div>
    <div id="map_canvas" style="width: 500px; height: 500px; float:left; border:3px #000000 solid; margin-left:20px;"></div>
    <div id="warnings_panel"></div>
    </body>
    </html>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  4. The Following User Says Thank You to jscheuer1 For This Useful Post:

    bluewalrus (12-13-2010)

  5. #4
    Join Date
    May 2007
    Location
    Boston,ma
    Posts
    2,127
    Thanks
    173
    Thanked 207 Times in 205 Posts

    Default

    Thanks. This appears is functioning correctly now, except for the math which I will workout. Is there a way to search the array for the lowest value, similar to the sort but where it would display the key of the array rather than just reordering them?

    Similiar to this in php

    PHP Code:
    $rewritting_count 0;
    foreach (
    $date as $value) {
        
    $lowest_date min($date);
        
    $lowest_value array_search($lowest_date$date);
        
    $re_write .= "\n" .  "$rewritting_count . Earlier: $month[$lowest_value]\"; \n More Detamils :$details[$lowest_value]\";\n";
        unset(
    $date[$lowest_value]);
        
    $rewritting_count++;

    Corrections to my coding/thoughts welcome.

  6. #5
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I'm having trouble following. Remember, my PHP isn't so hot and you don't show the initial values going in for what look to be important variables in your snippet (at least $date, and $re_write). And these don't appear to relate to the matter at hand anyway. In other words, the snippet appears a bit more generic than I would hope, even if I could follow it precisely.

    But I'm pretty sure all that can be mimicked in javascript. The min() function doesn't exist like that, but we could make one. However, in your snippet I see no key. For that:

    PHP Code:
    foreach ($date as $value) { 
    would have to be:

    PHP Code:
    foreach ($date as $key => $value) { 
    or some such. Or perhaps you're thinking in different terms that precludes the necessity of $key there.

    Anyways, imitating PHP with javascript (or any language with another) has its limitations. Often it's better to just define the objective and use the language you're in to do it.

    To that end, what's the ultimate objective here? I'm thinking it may be to display only the shortest distance, or perhaps to eliminate 0 distance(s) from the display, or something else? That's the real question here, what do you want the user to see?

    Also - what if anything do you need to make a record of (like in a database) and/or pass over to another function (like one from the map API)?
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #6
    Join Date
    Jan 2008
    Posts
    4,168
    Thanks
    28
    Thanked 628 Times in 624 Posts
    Blog Entries
    1

    Default

    Quote Originally Posted by jscheuer1 View Post
    The min() function doesn't exist like that, but we could make one.
    Math.min()? http://www.w3schools.com/jsref/jsref_min.asp But it doesn't use arrays.
    Jeremy | jfein.net

  8. #7
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 516 Times in 502 Posts
    Blog Entries
    5

    Default

    could you use Math.min() ? Can that method accept an array of numbers, or is there a (fairly simple) way to pass every member of an array into the parameter list?

  9. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Yes Math.min() could be used. As I said it could be done. However, it's not a direct translation. In PHP min() can scan all the array's values in one pass. In javascript it could but it's not intended to, so could screw up. It would be much safer to iterate over the array to do so.

    But, as I also said - it might be better to figure out the objective and work from there.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  10. #9
    Join Date
    May 2007
    Location
    Boston,ma
    Posts
    2,127
    Thanks
    173
    Thanked 207 Times in 205 Posts

    Default

    Yes, you are correct my goal here is to find the 3 shortest distances.

    The $date was an array containing a serious of values. The min function finds the lowest value in the array. It then searchs the array for the found value and get its key. I then use that key to pull the data from other arrays that have the same key and store it all into one variable (this part isn't important here I just need the 3 lowest values). I unset the value so it won't be found again and the loop repeats.
    Corrections to my coding/thoughts welcome.

  11. #10
    Join Date
    Jan 2008
    Posts
    4,168
    Thanks
    28
    Thanked 628 Times in 624 Posts
    Blog Entries
    1

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •