Go Back   CodingForums.com > :: Client side development > JavaScript programming > JavaScript frameworks

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-16-2012, 02:17 PM   PM User | #1
Leoa
New to the CF scene

 
Join Date: Mar 2012
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Leoa is an unknown quantity at this point
Values Disapearing from global arrays

Hi Everyone,
I'm trying to get multiple markers on a Google map using API V3. The markers I want to show are pink squares named beachflag.png. When my program gets to the setMarkers function the values inside the arrays created in the $.each loop are lost. The alert function displays undefined. I don't see how this is possible because I've declared this arrays at the beginning of the script (global). However, when the for loop at the bottom iterates through the location array it has only one value. All the values I pushed into the arrays (location, lat, and elong) are gone. I have been following an example from google sample api for v3(https://google-developers.appspot.co...mplex?hl=fr-FR) and it is not working for me. Here is my live test page"http://leobee.com/otakufinder/


Code:
var userLat="";

var userLong="";

var map;

var eventsLat=[];

var eventsLong=[];

var eventmarkersArray=[];

locations=[];

var i=0;

  jQuery(window).ready(function(){

                jQuery("#btnInit").click(initiate_geolocation);

            });

            function initiate_geolocation() {

            	//watch position
                navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);

            }

            function handle_errors(error)
            {
                switch(error.code)
                {
                    case error.PERMISSION_DENIED: alert("user did not share geolocation data");
                    break;

                    case error.POSITION_UNAVAILABLE: alert("could not detect current position");
                    break;

                    case error.TIMEOUT: alert("retrieving position timed out");
                    break;

                    default: alert("unknown error");
                    break;
                }
            }

            function handle_geolocation_query(position){


                userLat=position.coords.latitude;

				userLong=position.coords.longitude;

	/*
				var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
*/ 				var userLocation = new google.maps.LatLng(userLat, userLong);

				var mapOptions = {
          				zoom: 8,
         				center: userLocation,
         				mapTypeId: google.maps.MapTypeId.ROADMAP
        		};

 				map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);


 				var marker= new google.maps.Marker({
				position: new google.maps.LatLng(userLat, userLong),
				title: "Hello Testing",
				clickable: true,
				map: map
				});


                      // here use $.get to send info to php page for server processing

                      //$.get('http://localhost/otakufinder/scripts/geoloco.php?userLat='+userLat+'&userLong='+userLong+'&randNum='+numRand,


			 var numRand = Math.floor(Math.random()*1000)

              $.get('http://leobee.com/otakufinder/scripts/geoloco.php?userLat='+userLat+'&userLong='+userLong+'&randNum='+numRand,



					function (data){


						var jsontext = data;

						var contact = JSON.parse(jsontext);




						$.each(contact , function() {

   							 $('#otakuEvents').append(
        					'<div>'
        					+ this.event_name
        					+ '</div><div>'
       						+ this.lat +"  "+this.elong
       						+
        					'</div>'


   						 );// end div
				eventsLat.push(this.lat);


				eventsLong.push(this.elong);

				locations.push(this.event_name);


				});// end .each


setMarkers(map,locations);

function setMarkers(map, locations) {
alert (" inside function "+ eventsLat[i]);

// Add markers to the map
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var image = new google.maps.MarkerImage('images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels tall.
new google.maps.Size(20, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(0, 32));
var shadow = new google.maps.MarkerImage('images/beachflag.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
// Shapes define the clickable region of the icon.
// The type defines an HTML &lt;area&gt; element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
alert (" inside for loop "+ eventsLat[i]);
var myLatLng = new google.maps.LatLng(eventLat[0], eventLong[0]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,

});
}
}



			}// end data callback

		);// end getJson


 }
can you look over this code and let me know where I'm going wrong?
Leoa is offline   Reply With Quote
Old 03-16-2012, 02:28 PM   PM User | #2
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,261
Thanks: 10
Thanked 533 Times in 527 Posts
devnull69 will become famous soon enough
I think you stumbled upon the "asynchronity trap". In handle_geolocation_query you start a $.get()-Request, which is per definitionem an asynchronous call.

This means, that your normal program flow continues while the request is being processed by the server. Only in the callback of the request you are pushing elements into the array, but you try to access the array before(!) the request finishes and reaches this callback.
devnull69 is offline   Reply With Quote
Old 03-17-2012, 08:19 AM   PM User | #3
Leoa
New to the CF scene

 
Join Date: Mar 2012
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Leoa is an unknown quantity at this point
Holy smokes you are sooo right. I'm new at ajax stuff so thanks for pointing me in the right direction.
I finally got it to work!
Leoa is offline   Reply With Quote
Reply

Bookmarks

Tags
api v3, arrays, google, maps

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 10:37 AM.


Advertisement
Log in to turn off these ads.