Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Help needed defining (google) marker mysql 'id' in Javascript

Posted on 2008-10-17
10
Medium Priority
?
862 Views
Last Modified: 2011-10-19
Hey Experts,

This is a bit of a tricky one to explain so i hope that you can follow my explanation - please let me know if you need me to explain it further.

The attached bit of code is an excerpt from my site (www.globexposure.net/index_reg.php), which shows how my markers are set up. One aspect of this is:

onCloseFn: local_region

which is Google Maps API command that instructs the infowindow what to do in the event that an infowindow is closed. local_region is a function:

function local_region() {
          var marker.[id] = {locations['reg_id']};
            map.setCenter(marker.getPoint(reg_lat,reg_lon),maxZoom(reg_maxzl));
            }

I need help with the first line of this function - i am trying to define what the marker 'id' will be.
The marker, whose infowindow is being closed, is from the MySQL 'locations' table in which there is an 'reg_id' field, holding the id of the nearest regional marker. So, I want to set var marker to have an 'id' equal to the locations['reg_id'] of the marker being closed...


Really hope we can fix this & many thanks for your help
// A function to create the marker and set up the event window
      function createMarker(point,name,infotitle,html,icontype,maxZoom) {
        // === create a marker with the requested icon ===
        var marker = new GMarker(point, gicons[icontype]);
			if(icontype == 'pushpin' || icontype == 'arrow') {
				GEvent.addListener(marker, "click", function() {
				  // map.setCenter(marker.getPoint(),maxZoom,G_SATELLITE_MAP);
				  map.setCenter(marker.getPoint(),maxZoom);//no infowindow only center on point,maxZoom and maptype
				});
			}else{
		        GEvent.addListener(marker, "click", function() {
				  marker.openInfoWindowHtml("!",{buttons:{restore:{show:4}}, maxContent: html, maxTitle: infotitle, noCloseOnClick: true, onCloseFn: local_region});
				  window.setTimeout(function(){map.getInfoWindow().maximize()},200);  
		        });
			}
 
        // This function returns the map to the local region map extent
		function local_region() {
			var marker id = {locations['reg_id']}
            map.setCenter(marker.getPoint(reg_lat,reg_lon),maxZoom(reg_maxzl));
		}

Open in new window

0
Comment
Question by:Daniish
[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
  • 5
  • 5
10 Comments
 
LVL 82

Expert Comment

by:hielo
ID: 22753700
assuming:
locations['reg_id']

is your php variable that contains the id value you are referring to, try:


var marker={"id": "<?php echo locations['reg_id'];?>"};

Open in new window

0
 

Author Comment

by:Daniish
ID: 22754331
I get the following error for your line of code:

Parse error: syntax error, unexpected '[', expecting ',' or ';' in /home/sites/globexposure.net/public_html/index_reg.php on line 127
0
 
LVL 82

Expert Comment

by:hielo
ID: 22759416
are you printing/sending the javascript above from a php heredoc? You need to provide useful feedback. I don't know what your code looks like.
0
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 

Author Comment

by:Daniish
ID: 22759681
I'm not familiar with the term 'php heredoc' - i'll do some reading and let you know.
In the meantime i will attach my script for reference.
index-reg.php.txt
0
 
LVL 82

Expert Comment

by:hielo
ID: 22759820
read comments in code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Google Maps</title>
	<base href="http://www.globexposure.net/" />
	<link rel="stylesheet" type="text/css" href="style.css" />
<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=ABQIAAAAkF0zqR7ZiMsg19oFDTfnjRQg6eIn0pFX9mvfQfUyzLbmiRU2pRQw7d1UKMuUcsccdrIZomDJwpWVKQ" type="text/javascript"></script>
 
<script type="text/javascript" src="highslide/highslide.js"></script>
 
 
<script type="text/javascript">
  // remove the registerOverlay call to disable the controlbar
  hs.registerOverlay(
          {
            thumbnailId    : null,
            overlayId      : 'controlbar',
            position       : 'top right',
            hideOnMouseOut : true
          }
        );
  hs.graphicsDir = '../highslide/graphics/';
  hs.outlineType = 'rounded-white';
  // Tell Highslide to use the thumbnail's title for captions
  hs.captionEval = 'this.thumb.title';
</script>
 
 
</head>
 
<body onunload="GUnload()">
 
  <div id="wrap">
    <div id="navigation" style="background: url('images/navigation.jpg') no-repeat; width:100%">
	</div>
	<div id="body">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
 
      <tr> 
	    <td width="63%" rowspan="3">
 
		<div id="display_map" style="height: 500px; overflow: hidden"></div></td>
              <div id="controlbar" class="highslide-overlay controlbar">
                <a href="#" class="previous" onclick="return hs.previous(this)" title="Previous (left arrow key)"></a>
                <a href="#" class="next" onclick="return hs.next(this)" title="Next (right arrow key)"></a>
                <a href="#" class="highslide-move" onclick="return false" title="Click and drag to move"></a>
                <a href="#" class="close" onclick="return hs.close(this)" title="Close"></a>             
			  </div>	
          </td><!--  moved up to display_map div to make page align properly -->
 
      </tr>
    </table>
 
    </div>
	<div id="footer" width="100%"></div>
</div>
<!--
<?php
if ($handle = opendir('travel_pics/'.$id.'/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "
<a id='thumb1' href='/travel_pics/$id/$file/' onclick='return hs.expand(this)' class='highslide'>
<img src='../thumbphp/phpThumb.php?src=/travel_pics/$id/$file/&w=100' alt=''/>
</a>
";
}
}
closedir($handle);
}
?> 
-->
 
    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>
<?php
//you need to query your db here and extract the desired value for locations['reg_id']
//for purposes of testing I've included a "fake" id so that the "
locations=array('reg_id'=>2);
?>
    <script type="text/javascript">
    //<![CDATA[
 
    if (GBrowserIsCompatible()) {
      // this variable will collect the html which will eventually be placed in the side_bar
      var side_bar_html = "";
    
      // arrays to hold copies of the markers and html used by the side_bar
      // because the function closure trick doesnt work there
      var gmarkers = [];
      var htmls = [];
      var i = 0;
      
	  var baseIcon = new GIcon();
          baseIcon.iconSize = new GSize(32, 32);
          baseIcon.shadowSize = new GSize(56, 32);
          baseIcon.iconAnchor = new GPoint(16, 32);
          baseIcon.infoWindowAnchor = new GPoint(16, 0);
 
      // === Create an associative array of GIcons() ===
      var gicons = [];
      gicons["arrow"] = new GIcon(G_DEFAULT_ICON, "icon/arrow.png");
      gicons["pushpin"] = new GIcon(baseIcon, "icon/pushpin.png",null,"icon/shadow-pushpin.png");
      gicons["photo"]  = new GIcon(baseIcon, "icon/photo.png",null,"icon/shadow.png");
      gicons["home"]  = new GIcon(baseIcon, "icon/home.png",null,"icon/shadow.png");
      gicons["culture"]  = new GIcon(baseIcon, "icon/culture.png",null,"icon/shadow.png");
      gicons["party"]  = new GIcon(baseIcon, "icon/home.png",null,"icon/shadow.png");
	  gicons["food"]  = new GIcon(baseIcon, "icon/food.png",null,"icon/shadow.png");
	  gicons["accom"]  = new GIcon(baseIcon, "icon/home.png",null,"icon/shadow.png");
	  gicons["airport"]  = new GIcon(baseIcon, "icon/airport.png",null,"icon/shadow.png");
      gicons["sport"]  = new GIcon(baseIcon, "icon/sport.png",null,"icon/shadow.png");
	  
      // A function to create the marker and set up the event window
      function createMarker(point,name,infotitle,html,icontype,maxZoom) {
        // === create a marker with the requested icon ===
        var marker = new GMarker(point, gicons[icontype]);
			if(icontype == 'pushpin' || icontype == 'arrow') {
				GEvent.addListener(marker, "click", function() {
				  // map.setCenter(marker.getPoint(),maxZoom,G_SATELLITE_MAP);
				  map.setCenter(marker.getPoint(),maxZoom);//no infowindow only center on point,maxZoom and maptype
				});
			}else{
		        GEvent.addListener(marker, "click", function() {
				  marker.openInfoWindowHtml("!",{buttons:{restore:{show:4}}, maxContent: html, maxTitle: infotitle, noCloseOnClick: true, onCloseFn: local_region});
				  window.setTimeout(function(){map.getInfoWindow().maximize()},200);  
		        });
			}
 
        // This function returns the map to the local region map extent
		function local_region() {
			<?php echo 'var marker={"id": ' . locations['reg_id'] . '};'; ?>
            map.setCenter(marker.getPoint(reg_lat,reg_lon),maxZoom(reg_maxzl));
		}
		
		// save the info we need to use later for the side_bar
        gmarkers[i] = marker;
        htmls[i] = html;
        // add a line to the side_bar html
        side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
        i++;
        return marker;
      }
 
 
      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        gmarkers[i].openInfoWindowHtml(htmls[i]);
      }
      // === discard all except the first two results ===// moved this
          function doSearchCompleteCallback(search) { search.results.splice(2); }
 
		  // create the map and its zoom/pan controls
	      var map = new GMap2(document.getElementById("display_map"),{googleBarOptions:
          {onSearchCompleteCallback:doSearchCompleteCallback}
	      }); 
          
		  var mini = new GOverviewMapControl(); 
 
	      map.addMapType(G_PHYSICAL_MAP);
          map.addMapType(G_SATELLITE_3D_MAP);
		  map.addControl(new GLargeMapControl());
		  map.addControl(new GHierarchicalMapTypeControl());
		  map.addControl(mini);
		  mini.hide(); 
		  map.enableDoubleClickZoom();
	      map.enableScrollWheelZoom();
	  	  map.enableContinuousZoom();
		  map.enableGoogleBar();
          map.setCenter(new GLatLng(52.580, 11.6367), 4);
		  map.getInfoWindow();
		  var markerManager = new GMarkerManager(map, {borderPadding:1});
		  
		  // ====== Restricting the range of Zoom Levels =====
		  G_PHYSICAL_MAP.getMinimumResolution = function () { return 2 };
		  G_NORMAL_MAP.getMinimumResolution = function () { return 2 };
	  	  G_SATELLITE_MAP.getMinimumResolution = function () { return 2 };
		  G_HYBRID_MAP.getMinimumResolution = function () { return 2 };
 
      
          var ge;
          function getEarthInstanceCB(object) {
             ge = object;
             // You can now manipulate ge using the full Google Earth API.
          }
 
      var request = GXmlHttp.create();
	  var pts = [];
      request.open("GET", "http://www.globexposure.net/includes/read.php", true);
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          var xmlDoc = GXml.parse(request.responseText);
          // obtain the array of markers and loop through it
          var markers = xmlDoc.documentElement.getElementsByTagName("poi_markers"); 
          for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(lat,lng);
			var label = markers[i].getAttribute("name");
			var minZoom = parseFloat(markers[i].getAttribute( "minzl" ) );
			var maxZoom = parseFloat(markers[i].getAttribute( "maxzl" ) );
			//GLog.write('name  ' + label + '  min  ' + minZoom + '  max  ' + maxZoom);
            var description = markers[i].getAttribute("description");
            var photo = markers[i].getAttribute("photo");//photo is a problem in xml file
			var date = markers[i].getAttribute("date");
			var poi_id = markers[i].getAttribute("poi_id");
			var reg_id = markers[i].getAttribute("reg_id");
			var title = markers[i].getAttribute("title");
			var links = markers[i].getAttribute("links");
			//GLog.write(title);
			//GLog.write(photo);
			var infotitle = '<div id="infotitle">POI: ' + poi_id +' - '+ label +'</div>';
			var html ='<div id="infowindow"><div id="infodescr" style="overflow-x:hidden"><h1>' + title + '</h1>' + description + '</div><div id="infolinks">' + links + '</div><div id="infofooter">I was here on the ' + date + '</div></div>';
            // === read the icontype attribute ===
            var icontype = markers[i].getAttribute("icon");
			//GLog.write(icontype);
			
            // === create the marker, passing the icontype string ===
            var marker = createMarker(point,label,infotitle,reg_id,html,icontype,maxZoom);
			markerManager.addMarker(marker,minZoom,maxZoom);
	     }
	     
		 var markers = xmlDoc.documentElement.getElementsByTagName("regional_markers");
		 for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(lat,lng);
			var label = markers[i].getAttribute("name");
			var minZoom = parseFloat(markers[i].getAttribute( "minzl" ) );
			var maxZoom = parseFloat(markers[i].getAttribute( "maxzl" ) );
			//GLog.write('name  ' + label + '  min  ' + minZoom + '  max  ' + maxZoom);
            var description = markers[i].getAttribute("description");
            var photo = markers[i].getAttribute("photo");//photo is a problem in xml file
			var reg_id = markers[i].getAttribute("id");
			var nat_id = markers[i].getAttribute("nat_id");
			var title = markers[i].getAttribute("title");
			var links = markers[i].getAttribute("links");
			//GLog.write(title);
			//GLog.write(photo);
			var infotitle = '<div id="infotitle">Region: ' + reg_id +' - '+ label +'</div>';
			var html ='<div id="infowindow"><div id="infodescr"><h1>' + title + '</h1>' + description + '</div><div id="regional_poi">This is where i need a php script to display the result of its sql query for poi in this region</div><div id="infofooter"></div></div>';
            // === read the icontype attribute ===
            var icontype = markers[i].getAttribute("icon");
			//GLog.write(icontype);
			
            // === create the marker, passing the icontype string ===
            var marker = createMarker(point,label,infotitle,html,icontype,maxZoom);
			//map.addOverlay(marker); 
			markerManager.addMarker(marker,minZoom,maxZoom);
	     }
 
		 var markers = xmlDoc.documentElement.getElementsByTagName("national_markers");
		 for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(lat,lng);
			var label = markers[i].getAttribute("name");
			var minZoom = parseFloat(markers[i].getAttribute( "minzl" ) );
			var maxZoom = parseFloat(markers[i].getAttribute( "maxzl" ) );
			//GLog.write('name  ' + label + '  min  ' + minZoom + '  max  ' + maxZoom);
            var nat_id = markers[i].getAttribute("id");
			var infotitle = '<div id="infotitle">Country: ' + nat_id +' - '+ label +'</div>';
			var html = '<div id="infowindow"><div id="infodescr"><h1>No Infowindow should be displayed</h1></div><div id="infofooter"></div></div>';
			// === read the icontype attribute ===
            var icontype = markers[i].getAttribute("icon");
			//GLog.write(icontype);
			
            // === create the marker, passing the icontype string ===
            var marker = createMarker(point,label,infotitle,html,icontype,maxZoom);
			//map.addOverlay(marker); 
			markerManager.addMarker(marker,minZoom,maxZoom);
	     }
/*
        // ========= Now build the photo array and pass to Highslide ==========
		var imageArray = new Array();   
        if ( $dir = opendir ( 'travel_pics/'.$id.'/' ) )
        {
                while ( $file = readdir ( $dir ) )
                {
                        if ( $file != '.' && $file != '..' )
                        {
                                $imgArray[] = $file;
                        }
                }
        }
        closedir ( $dir );
        sort ( $imgArray );
        foreach ( $imgArray as $img )
        {
                echo ( "imageArray.push('$img');" );    
        }
        ?>
        // ====================================================================
 
*/
        // ========= Now process the polylines ===========	
		var lines = xmlDoc.documentElement.getElementsByTagName( "poi_route" );
        // The tessellate property breaks the line up into smaller sections (http://code.google.com/apis/earth/documentation/introduction.html#linestring)
		// lines.setTessellate(true);
		// read each line
        for ( var a = 0; a < lines.length; a++ ) {
 
        // get any line attributes
        // var colour = lines[a].getAttribute("colour");
        // var width  = parseFloat(lines[a].getAttribute("width"));
 
        // read each point on that line
 
        var points = lines[a].getElementsByTagName("point");
        var pts = [];
        var sTo = "";  
        for ( var i = 0; i < points.length; i++ ) {
           pts[ i ] = new GLatLng( parseFloat( points[ i ].getAttribute( "lat" ) ),
                            parseFloat( points[ i ].getAttribute( "lng" ) ) );
           if(i==0) sTo+="from: ";
           else sTo+="to: ";
           sTo+=points[i].getAttribute("lat");
           sTo+=",";
           sTo+=points[i].getAttribute("lng");
           sTo+=" ";
           }
		             
        map.addOverlay(new GPolyline(pts));
        // This draws the straight-line but if i comment it out No route appears for India because GDirections isn't supported there!
		
		function handleErrors() {
			map.addOverlay( new GPolyline( pts ) );
		}
		
		}
		// if we use the following instead: 'gdir = new GDirections(map);' then it displays a GDirection route BUT also displays the straight-line :(
		gdir = new GDirections();
		GEvent.addListener(gdir, "error", handleErrors);
		// alert (sTo);
		gdir.load(sTo, {preserveViewport:true} );
 
				
        // ================================================ 
		  
          // put the assembled side_bar_html contents into the side_bar div
          //document.getElementById("side_bar").innerHTML = side_bar_html;
        }
      }
      request.send(null);
    }
 
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
    // This Javascript is based on code provided by the
    // Blackpool Community Church Javascript Team
    // http://www.commchurch.freeserve.co.uk/   
    // http://econym.googlepages.com/index.htm
 
    //]]>
    </script>
 
  </body>
 
</html>

Open in new window

0
 

Author Comment

by:Daniish
ID: 22760255
Can you explain this line of code, Hielo:

//you need to query your db here and extract the desired value for locations['reg_id']
//for purposes of testing I've included a "fake" id so that the "

locations=array('reg_id'=>2);


At present my browser reports:
Parse error: syntax error, unexpected '=' in /home/sites/globexposure.net/public_html/index_heredoc.php on line 82

Thanks again
0
 
LVL 82

Accepted Solution

by:
hielo earned 2000 total points
ID: 22760367
my apologies. That is a variable, so it needs to start with a dollar sign:
$locations=array('reg_id'=>2);

similarly this:
<?php echo 'var marker={"id": ' . locations['reg_id'] . '};'; ?>
 
should be:
<?php echo 'var marker={"id": ' . $locations['reg_id'] . '};'; ?>
 
 
as a matter of fact, the same issue appears on my very first suggestion:
var marker={"id": "<?php echo $locations['reg_id'];?>"};
 
 
>>Can you explain this line of code
from your problem description, you will be querying a db and from the result you will extract reg_id. Ultimately you will have an associative array with the reg_id in question. I am just "simulating" the results. Basically that line is initializing:
$locations['reg_id'] to 2.

Open in new window

0
 

Author Comment

by:Daniish
ID: 22907518
Sorry its taken me yonks to come back to you...

I have tried to implement your code, using a static region (reg_id => 1) but this produces an odd result - a blank screen with no errors or warnings reported by Firebug:

www.globexposure.net/index_regionfocus.php


Can you spot anything perculiar ?
0
 
LVL 82

Expert Comment

by:hielo
ID: 22919213
>>using a static region (reg_id => 1)
in what I suggested earlier, reg_id needs to be quoted.

$locations=array('reg_id'=>1);
0
 

Author Comment

by:Daniish
ID: 22920212
I had the quotes but had forgotten to put a $ sign at the front of locations - but it still doesn't work!
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
Without even knowing it, most of us are using web applications on a daily basis.  In fact, Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We generally confuse these web applications to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

660 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