Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Long time reader, first time poster. Hoping you all can help me out. I'm an absolute novice to PHP and JavaScript but am strong with HTML, and have past experience with Google Maps but this is a bit of a new approach for me. Also my first time utilizing the V3 Google Maps API.

Background Information

I'm trying to rewrite a mileage calculator for my company that was broken because it used an old Yahoo Maps API, and I am so close to cracking it I can taste it! I've been able to feel myself around and learn a little about PHP from what was left behind by the past programmer but I'm having trouble finishing one last bit.

The code pasted below utilizes a separate PHP file (getaddress.php) and the ?cid=FOOBAR from the URL to query our MySQL database and pull the customer's address and generate a Google Map / Driving Directions page.

My struggle is with getting the data pulled from the database into the var "route" in the tag for the Google Map display. I'm able to echo it perfectly with:

<?php echo "Directions to " . $_GET['cid'];?>

but I'm unable to come up with a way to get that same text echoed into the route variable. I'm a little embarrassed in asking this because I'm certain it's something simple I'm just overlooking but it's one of those kind of "don't know what you're looking for to search for a solution" kind of things, so I'm turning to you all and your talents.

The "origin: '123 Easy Street' will always be hard coded, so that isn't a problem. The problem is the "destination: " which I would like to populate with the information getaddress.php pulls from the database, which looks like "1234 Easy Street 46142" in the HTML body.

Does anyone have any suggestions on how I can get that address string into the "destination: " portion of the route variable in the JavaScript?

I graciously appreciate any alternative ideas you all can suggest. I'm stumped.

getGmap.php Code

<?php require('constants.php');?>
<?php require('sessionHandler.php');?>
<?php require('dbHandler.php');?>
<?php if (!isset($_GET['cid']) || empty($_GET['cid'])) die('No company specified.');?>

<!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"  xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <title>Driving Directions to Customer provided by Google Maps</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <link type="text/css" href="./lib/default.css" rel="stylesheet">

  <script type="text/javascript"
           src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnWPIRN8X0gLNqz-c1d87gv84CwZDuzjc&sensor=false"></script>

  <script>

        function process(){
                //Main processing starts here.
                //call getAddress. 
                getAddress();
        }

        //*** Get company information from database ***
        var req;                //global http request object

        function getAddress(){
                var url="getaddress.php?ajax=1&cid=<?php echo $_GET['cid'];?>";
                if (window.XMLHttpRequest) {    // IE/Windows ActiveX version
                req = new XMLHttpRequest();
                req.onreadystatechange = processReqChange;
                req.open("GET", url, true);
                req.send(null);
          }
          else if (window.ActiveXObject) {
                req = new ActiveXObject("Microsoft.XMLHTTP");
                if (req) {
                    req.onreadystatechange = processReqChange;
                    req.open("GET", url, true);
                    req.send();
                }
          }
          return true;
        }

        //*** End get company information from database ***

    </script>
  </head>

  <body onload="process()">
        <font class="normalText"><b>
        <?php echo "Directions to " . $_GET['cid'];?>
        <span id="addressSpan"></span>
        from 123 Easy Street
        </b></font>
        <br />
        <font class="normalText10">
        <div style="width: 600px;">
             <div id="map" style="width: 280px; height: 400px; float: left;"></div>
             <div id="panel" style="width: 300px; float: right;"></div>
        </div>
        </font>
        <script type="text/javascript">

             var directionsService = new google.maps.DirectionsService();
             var directionsDisplay = new google.maps.DirectionsRenderer();

             var map = new google.maps.Map(document.getElementById('map'), {
               zoom:7,
               mapTypeId: google.maps.MapTypeId.ROADMAP
             });

             directionsDisplay.setMap(map);
             directionsDisplay.setPanel(document.getElementById('panel'));

             var route = {
               origin: '123 Easy Street',
               destination: '1234 Easy Street 46142',
               travelMode: google.maps.DirectionsTravelMode.DRIVING
             };

             directionsService.route(route, function(response, status) {
               if (status == google.maps.DirectionsStatus.OK) {
                 directionsDisplay.setDirections(response);
               }
             });
        </script>
  </body>
</html>

getaddress.php Code

<?php require('constants.php'); ?>
<?php require('sessionHandler.php'); ?>
<?php require('dbHandler.php'); ?>
<?php

if (isset($_GET['cid']) && !empty($_GET['cid'])) {
        //we only pass 5 chars of short id - actual id may be longer
        $query="select Address1, City, State, Zipcode from companies where CompanyShortID like '".$_GET['cid']."%'";
}
else
        die('Error: No company specified.');

dbConnect();
$result=mysql_query($query);
if (!$row=mysql_fetch_array($result))   // no records returned
        echo "";
else {
        echo $row['Address1']." ".$row['Zipcode'];
}
exit;
?>
share|improve this question
    
Given that you're pasting that value into client-side code which simply returns the SAME value back to your server, why bother with a JS round-trip at all? Save it in the server-side session... –  Marc B Oct 1 '13 at 21:39
    
Marc B -- thank you for taking the time to comment. Again, I'm a PHP/JavaScript novice (if even that...) so I'm not sure I follow your response. Could you go into a bit more detail? Sample code? –  Michael P Oct 1 '13 at 21:48
    
(1) It's not clear where cid originates. It appears to be passed to "getGmap.php", which passes it to "getaddress.php", but we don't know where it comes from. (2) The composition of "getGmap.php" implies that the page is reloaded for every new cid, which is not a great idea as every reload of the page will involve a reload of the Google map, eating into your free quota of map loads. You need to develop "getGmap.php" as a persistent page that does not need to be reloaded. That's top priority, then worry about getting it to fetch data from "getaddress.php". –  Beetroot-Beetroot Oct 1 '13 at 23:05
    
Beetroot-Beetroot - Thanks for your response. cid originates from the URL (example: /getGMap.php?cid=FOO). Thank you for your suggestion about our quota. This will be used by a very small number of people but I will certainly look at avoiding a reload once I get the page working properly. –  Michael P Oct 1 '13 at 23:28
    
I got it working! Did a little revamping of getaddress.php and i was able to set my destination equal to "destination: '<?php echo getAddress($_GET["cid"]); ?>',". I'll post the updated code for everyone's benefit when I get a chance. –  Michael P Oct 2 '13 at 0:05

1 Answer 1

up vote 0 down vote accepted

As promised, here is the code I was able to get working.

getGmap.php Code

<?php require('constants.php');?>
<?php require('sessionHandler.php');?>
<?php require('dbHandler.php');?>
<?php require('getaddress.php');?>

<?php

if (!isset($_GET['cid']) || empty($_GET['cid']))
     die('No company specified.');
?>

<!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"  xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <title>Driving Directions to Customer provided by Google Maps</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <link type="text/css" href="./lib/default.css" rel="stylesheet">

        <script type="text/javascript"
           src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnWPIRN8X0gLNqz-c1d87gv84CwZDuzjc&sensor=false"></script>

        <script>

                function process(){
                        //Main processing starts here.
                        //call getAddress. When AJAX call completes it will call inititalizeMap() to show the map.
                        getAddress();
                }


        //*** Begin AJAX***
        var req;                //global http request object

        function getAddress(){
                var url="getaddress.php?ajax=1&cid=<?php echo $_GET['cid'];?>";

                if (window.XMLHttpRequest) {    // IE/Windows ActiveX version
                req = new XMLHttpRequest();
                req.onreadystatechange = processReqChange;
                req.open("GET", url, true);
                req.send(null);
          }
          else if (window.ActiveXObject) {
                req = new ActiveXObject("Microsoft.XMLHTTP");
                if (req) {
                    req.onreadystatechange = processReqChange;
                    req.open("GET", url, true);
                    req.send();
                }
          }
          return true;
        }

        function processReqChange()
        {
            // only if req shows "complete"
            if (req.readyState == 4) {  //4=completed
                // only if "OK"
                if (req.status == 200) {        //200=OK, so processing data
                    //alert(req.responseText);

                    //parse XML
                    //var response  = req.responseXML.documentElement;
                                toAddress=req.responseText;
                                document.getElementById('addressSpan').innerHTML=" - "+toAddress;
                                initializeMap();
                }
                else {
                    alert("There was a problem retrieving the XML data:\n" + req.statusText);
                }
            }
        }
        //****** End AJAX ***
    </script>
  </head>

  <body onload="process()">
        <font class="normalText"><b>
        Directions to: <?php echo $_GET["cid"]. "-". getAddress($_GET["cid"]); ?>
        <span id="addressSpan"></span>
        from: My Office - 1234 Easy Street
        </b></font>
        <br />
        <font class="normalText10">
        <div style="width: 600px;">
             <div id="map" style="width: 280px; height: 400px; float: left;"></div>
             <div id="panel" style="width: 300px; float: right;"></div>
        </div>
   <script type="text/javascript">

             var directionsService = new google.maps.DirectionsService();
             var directionsDisplay = new google.maps.DirectionsRenderer();

             var map = new google.maps.Map(document.getElementById('map'), {
               zoom:7,
               mapTypeId: google.maps.MapTypeId.ROADMAP
             });

             directionsDisplay.setMap(map);
             directionsDisplay.setPanel(document.getElementById('panel'));

             var route = {
               origin: '1234 Easy Street',
               destination: '<?php echo getAddress($_GET["cid"]); ?>',
               travelMode: google.maps.DirectionsTravelMode.DRIVING
             };

             directionsService.route(route, function(response, status) {
               if (status == google.maps.DirectionsStatus.OK) {
                 directionsDisplay.setDirections(response);
               }
             });
           </script>
        <br/>
    </font>
  </body>
</html>

getaddress.php Code

<?php

    function getAddress($cid) {

            //we only pass 5 chars of short id - actual id may be longer
            $query="select Address1, City, State, Zipcode from companies where CompanyShortID like '" . $cid . "%'";

            dbConnect();
            $result=mysql_query($query);
            if (!$row=mysql_fetch_array($result))   // no records returned
                            return "Company Not Found";
            else {
                            return $row['Address1']." ".$row['Zipcode'];
            }

            return "Company Not Found";
    }

?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.