2

I’m working on the example: “Using PHP/MySQL with Google Maps” https://developers.google.com/maps/articles/phpsqlajax_v3

I know this tutorial has been covered a lot before but I can’t find the answer I’m looking for, and hope someone can help.

I’m trying to show a Google Map with markers. Each marker is a book icon. Books are organised by category (I’ve called it “type” in my database). The idea is that users can select which category of book they want, and then only these books will be shown on the map.

My problem is I can’t get the FORM select to work, the “type” variable needs to be passed from the index.php to the page phpsqlajax_genxml2.php, in order for the database to be interrogated.

My question is - how do i get the php variable $type to the phpsqlajax_genxml2.php page?

The phpsqlajax_genxml2.php page is not included in the index.php page, but there is a downloadUrl function: downloadUrl("phpsqlajax_genxml2.php", function(data)

Here are my files in full. Thanks in advance

index.php

    <?php
    // Get parameters from URL
    $type = $_GET["type"];
    ?>


    <!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>PHP/MySQL & Google Maps Example</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
    <script type="text/javascript">
    //<![CDATA[

    var customIcons = {
      'Murder Mystery': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png'
      },
      'Travel Guide': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_gray.png'
      },
      'Romance': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_purple.png'
      },
      'Short Story': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
      },
      'Thriller': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      },
      'Comedy': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png'
      },
      'Graphic Novel': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_white.png'
      },
      'Satire': {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_brown.png'
      }

    };
</script>

<script type="text/javascript">

//Check if browser supports W3C Geolocation API

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  } else {
  alert('Geolocation is required for this page, but your browser doesn&apos;t support it. Try it with a browser that does, such as Opera 10.60.');
}

function errorFunction(position) {
  alert('Error!');
}

//If successful geolocation then draw the map, show my coords on the map, and pull in the icons

function successFunction(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
        var map = new google.maps.Map(document.getElementById("map"), 
        {
        center: new google.maps.LatLng(lat, lng),
        zoom: 13,
        mapTypeId: 'roadmap'
        });

        var infoWindow = new google.maps.InfoWindow;

      // SQL to XML file
      //downloadUrl("phpsqlajax_genxml2.php?type=" + type, function(data) {
      downloadUrl("phpsqlajax_genxml2.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + "<i>" + type + "</i>";
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
          bindInfoWindow(marker, map, infoWindow, html);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}

    //]]>

  </script>

  </head>

<body onload="successFunction(position)">

<div id="map" style="width: 500px; height: 400px"></div>

<form action="<?php $_PHP_SELF ?>" method="GET">
<select name="type">
  <option value="Murder Mystery">Murder Mystery</option>
  <option value="Travel Guide">Travel Guide</option>
  <option value="Romance">Romance</option>
  <option value="Short Story">Short Story</option>
  <option value="Thriller">Thriller</option>
  <option value="Comedy">Comedy</option>
  <option value="Graphic Novel">Graphic Novel</option>
  <option value="Satire">Satire</option>
</select>
<input type="submit" value="Submit" />
</form>

</body>

</html>

phpsqlajax_genxml2.php

<?php
// Get parameters from URL
$type = $_GET["type"];

include ("inc/DB_connect.php");

//Using PHP's echo to Output XML

function parseToXML($htmlStr) 
{ 
$xmlStr=str_replace('<','&lt;',$htmlStr); 
$xmlStr=str_replace('>','&gt;',$xmlStr); 
$xmlStr=str_replace('"','&quot;',$xmlStr); 
$xmlStr=str_replace("'",'&#39;',$xmlStr); 
$xmlStr=str_replace("&",'&amp;',$xmlStr); 
return $xmlStr; 
}


// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) 
{
  die ('Can\'t use db : ' . mysql_error());
}

// Select all the rows in the markers table
//$query = "SELECT * FROM `markers` WHERE 1";
$query = "SELECT * FROM `markers` WHERE `type` = '$type'";
$result = mysql_query($query) or die(mysql_error());

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result))
{
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}

// End XML file
echo '</markers>';

?>
1
  • Welcome to stackoverflow! In order to make it easier for other users to answer your questions (and thus attracting more and better answers), please make sure you only include whatever is necessary to describe your particular problem. Please see stackoverflow.com/help/mcve Commented Mar 11, 2015 at 9:40

1 Answer 1

1

So if you want to pass data from one PHP file to another, You have two options in this case, Cookies and Sessions:

Cookie:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

Session:

//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];

The big difference between sessions and cookies are that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.

EDIT

There is one more method supported where you can pass that variable in your JQuery call like this:

In your first file:

jQuery('#map').load('Firstfile.php?type=<?php echo($type);?>');

In your second file

$type = $_GET['type'];

Give this one a shot!!

Referred from Passing php variable from one file to another?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much AniV. I tried this but still the variable $type isn't being passed into phpsqlajax_genxml2.php. I can't work out why.
Thanks AniV - whereabouts should I put the code in the first file? At the top?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.