Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 19
  1. #1
    New Coder
    Join Date
    Sep 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Transferring JSON to Javascript to put into array type var

    Hello,

    I am trying to bring over JSON from a PHP to a javascript function in HTML, so I can fill my arrays of type var. When I do try to convert they turn into undefined when printed out through my google maps api infowindow functions.


    <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta charset="utf-8">
    <style type="text/css">
    html { height: 100% }
    body { height: 100%; margin: 0; padding: 0 }
    #map_canvas { height: 100% }
    </style>

    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>


    <script type="text/javascript"
    src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBwQFitNaBxkrOKQQ6zf944Rff6pqo9kmA&sensor=false">
    </script>

    <script type="text/javascript">

    function initialize() {
    var image = new Array();
    var infoWindowContent = new Array();
    var LatLngX = new Array();
    var LatLngY = new Array();
    var infowindow = new Array();
    var marker = new Array();
    var imageMarker = new Array();
    var imageIsWeekly = new Array();
    var contentName = new Array();
    var contentSpecial = new Array();
    var contentDow = new Array();
    var contentStartTime = new Array();
    var contentEndTime = new Array();
    var contentDescription = new Array();
    var fileData = new Array();

    var mapOptions = {
    center: new google.maps.LatLng(43.1008, -75.2331),
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };

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

    $(document).ready(function(){
    /* call the php that has the php array which is json_encoded */
    $.getJSON('ReturnPlacesJSON.php', function(data) {
    fileData.push(data);
    /* data will hold the php array as a javascript object */
    $.each(data, function(key, val) {
    //$('ul').append('<li id="' + key + '">' + val.name + ' ' + val.address + ' ' + val.xcoord + ' ' + fileData[0] + '</li>');<---------This works perfectly though
    contentName[0] = val.name; <-------------------------------------------------------This is where I am trying to convert the json to my array
    });
    });
    });

    image[0] = new google.maps.MarkerImage('images/beermug.png');
    image[1] = new google.maps.MarkerImage('images/beercup.png');

    imageIsWeekly[0] = 0;
    imageIsWeekly[1] = 1;

    //contentName[0] = '<a href="http://www.thecageutica.com/">The Cage</a>'
    contentSpecial[0] = '<p>$5 Burgers and Fries</p>'
    contentDow[0] = '<p>Monday</p>'
    contentStartTime[0] = '4:00 PM'
    contentEndTime[0] = 'Close'
    //contentDescription[0]

    infoWindowContent[0] = contentName + contentSpecial[0] + contentStartTime[0] + ' - ' + contentEndTime[0]; <------------This is where I am using it to store in the infowindow variable
    infoWindowContent[1] = '<p>Shane House</p>' + '<p>Karoke</p>' + '<p>All Day Every Day</p>';

    LatLngX[0] = 43.103569;
    LatLngX[1] = 43.048228;
    LatLngY[0] = -75.223008;
    LatLngY[1] = -75.278149;

    for (var i = 0; i < 2; i++)
    {
    if (imageIsWeekly[i] == 0)
    imageMarker[i] = image[0];
    else
    imageMarker[i] = image[1];

    infowindow[i] = new google.maps.InfoWindow({
    content: infoWindowContent[i]<---------------------------------------------------------------This is where it should display in the info window the the trigger is performed
    });

    marker[i] = new google.maps.Marker({
    position: new google.maps.LatLng(LatLngX[i], LatLngY[i]),
    map: map,
    icon: imageMarker[i],
    title: 'Click to zoom'
    });


    }

    google.maps.event.addListener(marker[0], 'click', function() {
    map.setZoom(16);
    map.setCenter(marker[0].getPosition());
    infowindow[0].open(map,marker[0]);
    });
    google.maps.event.addListener(marker[1], 'click', function() {
    map.setZoom(16);
    map.setCenter(marker[1].getPosition());
    infowindow[1].open(map,marker[1]);
    });

    }

    google.maps.event.addDomListener(window, 'load', initialize);

    </script>
    </head>
    <body onload="initialize()">
    <div id="map_canvas" style="width:100%; height:100%"></div>


    </body>
    </html>

    Everything else works, but the use of the JSON data from my PHP file.

    I've trying using objects variables to bring in the data or have the for each loop for my json bring in to fill the google map api data, but get worse results.

    Any ideas?

    Thanks

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    for example, if you are trying to populate the contentName array, you have to find a way of doing it by the array index. From what I can see,
    Code:
    contentName[0] = val.name;
    will just keep overwriting the first element in the array

    you would want to check what value key is returning, but it seems to me that something like this:
    Code:
    contentName[key] = val.name;
    is probably closer to it

  • #3
    New Coder
    Join Date
    Sep 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks that'll help in the future, but still returning undefined

  • #4
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    1. what exactly is returning undefined?
    2. what does the error console say?
    3. what's up with this line: trigger is performed?
    4. can you maybe give a link to your map? it would be simpler to debug that way.

  • #5
    New Coder
    Join Date
    Sep 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Sorry I mean the listener calls on that function

    The site is
    http://shanewmiller.com/Specials/map.html

    Thanks

  • #6
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    I guess it was a closure problem. I'm not sure, actually but anyway, it works if you create the marker in a separate function and attach the infowindow listener there directly. You get the bonus of only creating one infowindow, and moving it and setting its content depending on where the click happens.

    Your arrays aren't populated yet (you have to do this in the each function the way you do with the bar names) so some fields will come up undefined. Once you populate the arrays it should be ok, though...

    Code:
        <script type="text/javascript">
    		
        function initialize() {
    	  	var image = new Array();
    	    var infoWindowContent = new Array();
    	    var LatLngX = new Array();
    	    var LatLngY = new Array();
    	    var infowindow = new Array();
    	    var marker = new Array();
    		var imageMarker = new Array();
    		var imageIsWeekly = new Array();
    		var contentName = new Array();
    		var contentSpecial = new Array();
    		var contentDow = new Array();
    		var contentStartTime = new Array();
    		var contentEndTime = new Array();
    		var contentDescription = new Array();
    		var fileData = new Array();
    		var infoWindow = new google.maps.InfoWindow();
    	  
            var mapOptions = {
              center: new google.maps.LatLng(43.1008, -75.2331),
              zoom: 14,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
            var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    	
    		$(document).ready(function(){
    			/* call the php that has the php array which is json_encoded */
    			$.getJSON('ReturnPlacesJSON.php', function(data) {
    				fileData.push(data);
    				/* data will hold the php array as a javascript object */
    				$.each(data, function(key, val) {
    					contentName[key] = val.name;
    				});
    			});
    		});
    	
    	  	image[0] = new google.maps.MarkerImage('http://shanewmiller.com/Specials/images/beermug.png');
            image[1] = new google.maps.MarkerImage('http://shanewmiller.com/Specials/images/beercup.png');
    		
    		imageIsWeekly[0] = 0;
    		imageIsWeekly[1] = 1;
    		
    		//contentName[0] = '<a href="http://www.thecageutica.com/">The Cage</a>'
    		contentSpecial[0] = '<p>$5 Burgers and Fries</p>'
    		contentDow[0] = '<p>Monday</p>'
    		contentStartTime[0] = '4:00 PM'
    		contentEndTime[0] = 'Close'
    		//contentDescription[0]
    		
           	LatLngX[0] = 43.103569;
    		LatLngX[1] = 43.048228;
    		LatLngY[0] = -75.223008;
    		LatLngY[1] = -75.278149;
    		
    		for (var i = 0; i < 2; i++) 
    		{	
    			if (imageIsWeekly[i] == 0)
    				imageMarker[i] = image[0];
    			else	
    				imageMarker[i] = image[1];
    				
    		var latlng=new google.maps.LatLng(LatLngX[i], LatLngY[i]);
    		var icon=imageMarker[i];
    		var title= 'Click to zoom'
    		var html=contentName[i] + contentSpecial[i] + contentStartTime[i] + ' - ' + contentEndTime[i];
    		createMarker(latlng, icon, title,html,map,infoWindow)	
    		}
    	}
    	
    
    	function createMarker(latlng, icon, title,html,map,infoWindow) {
        var marker = new google.maps.Marker({
    	icon:icon,
            position: latlng,
            map: map
            });
    
        google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html); 
            infoWindow.open(map,marker);
            });
    	}
      
    	google.maps.event.addDomListener(window, 'load', initialize);
    	  
        </script>
    fwiw, it seems to me that you are making a lot of extra work by creating all those arrays to then create marker objects using the array elements. I would look at calling the createMarker function from directly inside the each and bypassing the middle step.

    fwiaw, I believe that adding the dom listener to call the initialize function onload means that you don't have to do <body onload="initialize()"> - in fact it's probably a bad idea as that function may end up getting called twice (being that body onload and window onload are separate events)

  • #7
    New Coder
    Join Date
    Sep 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts
    The onload on the body helped getting rid of that, but I tried to fill the rest of the arrays with the json information and still can't be read. Don't know y the json cant be changed into the var array seems its not transferring variables over correctly.

  • #8
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    did you try it with the code I posted?

  • #9
    New Coder
    Join Date
    Sep 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Yea that didn't really work either it kept the listener but the information it was bringing in to the info window was all screwed up for everyone but the first one defined

  • #10
    New Coder
    Join Date
    Sep 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts
    and still undefined

  • #11
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    Like I said: the first one (I assume we are talking about contentName) is defined because that array is now populated correctly. You will have to populate the other arrays correctly (within the each(), the same way as you do with contentName[key] = val.name;) for the rest of the infowindow info to display correctly.

    If it's still causing trouble, post a link to your updated map

  • #12
    New Coder
    Join Date
    Sep 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Alright the code has been changed on the site

  • #13
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    Have a look at the error console.

    But anyway - try loading this page in its entirety - the only thing different is that it the data is hardcoded rather than pulled in from the getJSON function:

    Code:
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <meta charset="utf-8">
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0; padding: 0 }
          #map_canvas { height: 100% }
        </style>
    	
    	<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
    	
    	<form>
    	<p align="center"><b>Select a Day </b>
    	<select id="setit" style="color: #0000FF" size="1" name="test">
    	<option value="">Select one</option>
        <option value="http://www.altavista.com">Monday</option>
       	<option value="http://www.yahoo.com">Tuesday</option>
      	<option value="http://www.google.com">Wednesday</option>
    	<option value="http://www.google.com">Thursday</option>
    	<option value="http://www.google.com">Friday</option>
    	<option value="http://www.google.com">Saturday</option>
    	<option value="http://www.google.com">Sunday</option></select>
       	<input type="button" value="Go"
    	onclick="window.open(setit.options[setit.selectedIndex].value)">
    	</p></form>
    
        <script type="text/javascript"
          src="http://maps.googleapis.com/maps/api/js?&sensor=false">
        </script>
    	
        <script type="text/javascript">
    		
        function initialize() {
    			var infoWindow = new google.maps.InfoWindow();
    	  
            var mapOptions = {
              center: new google.maps.LatLng(43.1008, -75.2331),
              zoom: 14,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
            var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    	
    		$(document).ready(function(){
    			/* call the php that has the php array which is json_encoded */
    		//	$.getJSON('ReturnPlacesJSON.php', function(data) {
    			//	fileData.push(data);
    				/* data will hold the php array as a javascript object */
    				$.each([{name:'<p>The Cage</p>',address:"401 Main St, Utica, NY",special:'<p>$5 Burgers and Fries</p>',day:'<p>Monday</p>',start:'4:00 PM',end:'Close',xcoord:43.103569,ycoord:-75.223008,img:'http://shanewmiller.com/Specials/images/beermug.png'},
    				{name:'<p>The Celtic Harp</p>',address:"805 Varick St, Utica, NY",xcoord:43.103251,ycoord:-75.243857,img:'http://shanewmiller.com/Specials/images/beercup.png'}], function(key, val) {
    				var latlng=new google.maps.LatLng(val.xcoord, val.ycoord);
    				var title= 'Click to zoom';
    				var icon=val.img;
    				var special=(val.special)?val.special:""
    				var end=(val.end)?val.end:""
    				var start=(val.start)?val.start+" - ":""
    				var day=(val.day)?val.day:""
    				var html=val.name + special + day + start + end;
    				createMarker(latlng, icon, title,html,map,infoWindow)
    				$('#list').append('<li id="' + key + '">' + val.name + ' ' + val.address + ' ' + val.xcoord + ' ' + val.ycoord + '</li>');		
    		//		});
    			});
    		});
    	
    		
    	//	imageIsWeekly[0] = 0;  //I don't know what these are supposed to do
    	//	imageIsWeekly[1] = 1;
    	
    	}
    
    	function createMarker(latlng, icon, title,html,map,infoWindow) {
        var marker = new google.maps.Marker({
    	icon:new google.maps.MarkerImage(icon),
            position: latlng,
            map: map
            });
    
        google.maps.event.addListener(marker, 'click', function() {
    	map.setZoom(16);
    			map.setCenter(marker.getPosition());
            infoWindow.setContent(html); 
            infoWindow.open(map,marker);
            });
    	}
      
    	google.maps.event.addDomListener(window, 'load', initialize);
    	  
        </script>
    </head>
    <body>
    	<div id="map_canvas" style="width:100%; height:100%"></div>
    	<ul id="list"></ul>
    </body>
    </html>

  • #14
    New Coder
    Join Date
    Sep 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Fixed the errors, but same output

    I changed the code as you wanted me too, so is there an issue with my JSON call then?

  • #15
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    no. the issue was that you weren't using the output correctly.

    from what I can see, all you have to do now is change your entire document.ready function (at this page) to this:

    Code:
    $(document).ready(function(){
    			/* call the php that has the php array which is json_encoded */
    			$.getJSON('ReturnPlacesJSON.php', function(data) {
    				/* data will hold the php array as a javascript object */
    				$.each(data, function(key, val) {
    				var latlng=new google.maps.LatLng(val.xcoord, val.ycoord);
    				var title= 'Click to zoom';
    				var icon=val.img;
    				var special=(val.special)?val.special:""
    				var end=(val.end)?val.end:""
    				var start=(val.start)?val.start+" - ":""
    				var day=(val.day)?val.day:""
    				var html=val.name + special + day + start + end;
    				createMarker(latlng, icon, title,html,map,infoWindow)
    				$('#list').append('<li id="' + key + '">' + val.name + ' ' + val.address + ' ' + val.xcoord + ' ' + val.ycoord + '</li>');		
    				});
    			});
    		});
    ... although really, if your initialize function is being called on window load and the above code is inside that function, wrapping it in a document ready function is kind of redundant, but that is a finer point and won't affect the outcome here.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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