Solved

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

Posted on 2008-10-17
10
856 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
  • 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
 

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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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 500 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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

747 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now