Search code examples
javascriptjquerymysqlgoogle-maps-api-2

Google Maps Script - Changing the static info with variables from the database loop


Ok, so I am trying to figure out how to include the below javascript/jquery google maps script in the loop. What I am wanting to do is replace the static information in the script and replace them with the variables outputted by the DB loop. I also have pagination setup to limit the query to 20 per a page. Please see here: http://clients.beckin.com/prince-corp/test/dealer-locator.php

I would like this script to only contain the information for each address that is listed in the table which is looped from the DB. How in the world can I do this?

Update: I have updated my Google Maps Script. Please see below. I was able to pass the variable into the script. However, how can I loop the variable in my database loop and contain them into the

  addresses =   [
        "<?php echo $myAddress; ?>",
        ];

section? Each page will loop with 20 address. How can I do that in the script?

http://clients.beckin.com/prince-corp/test/map_test.php

<?php
$myAddress= "117 Mitchell Blvd, Gadsden, 35904"; 
?>

Javacript Code:

<script type="text/javascript">
if (GBrowserIsCompatible()) { 

    var map = new GMap2(document.getElementById("map_canvas"));
    map.setUIToDefault();

    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);

    // Creates a marker whose info window displays the letter corresponding
    // to the given index.
    function createMarker(point, index) {
      // Create a lettered icon for this point using our icon class
      var letter = String.fromCharCode("A".charCodeAt(0) + index);
      var letteredIcon = new GIcon(baseIcon);
      letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

      // Set up our GMarkerOptions object
      markerOptions = { icon:letteredIcon };
      var marker = new GMarker(point, markerOptions);

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(addresses[index]);
      });
      return marker;
    }


  // ====== Create a Client Geocoder ======
  var geo = new GClientGeocoder(); 

  // ====== Array for decoding the failure codes ======
  var reasons=[];
  reasons[G_GEO_SUCCESS]            = "Success";
  reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
  reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
  reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
  reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
  reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
  reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
  reasons[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";

  var j=0;
  // ====== Geocoding ======
  function getAddress(search, next) {
    geo.getLocations(search, function (result)
      { 
        // If that was successful
        if (result.Status.code == G_GEO_SUCCESS) {
          // Lets assume that the first marker is the one we want
          var p = result.Placemark[0].Point.coordinates;
          var lat=p[1];
          var lng=p[0];
          if(j == 0)
          {
            map.setCenter(new GLatLng(lat, lng), 15);
          }

            var latlng = new GLatLng(lat, lng);
            map.addOverlay(createMarker(latlng, j));

        }
        j++;
        next();
      }
    );
  }


  // ======= An array of locations that we want to Geocode ========
  addresses =   [
        "<?php echo $myAddress; ?>",
        ];

  // ======= Global variable to remind us what to do next
  var nextAddress = 0;

  // ======= Function to call the next Geocode operation when the reply comes back

  function theNext() {
    if (nextAddress < addresses.length) {
      getAddress(addresses[nextAddress],theNext);
      nextAddress++;
    }
  }

  // ======= Call that function for the first time =======
  theNext();

}

// display a warning if the browser was not compatible
else {
  alert("Sorry, the Google Maps API is not compatible with this browser");
}

</script>

Solution

  • I found a way to do this :) Here is my solution with making google maps dynamically from a database query. I ended up just doing it with arrays. Hope this helps others ;)

    PHP

    $thisAddress[$i] = mysql_result($result, $i, 'address');
    $thisCity[$i] = MYSQL_RESULT($result,$i,"city");
    $thisState[$i] = MYSQL_RESULT($result,$i,"state");
    $thisZip[$i] = MYSQL_RESULT($result,$i,"zip");
    
    <?php
    $thisAddress0 = "$thisAddress[0], $thisCity[0], $thisState[0] $thisZip[0]"; 
    $thisAddress1 = "$thisAddress[1], $thisCity[1], $thisState[1] $thisZip[1]"; 
    $thisAddress2 = "$thisAddress[2], $thisCity[2], $thisState[2] $thisZip[2]"; 
    $thisAddress3 = "$thisAddress[3], $thisCity[3], $thisState[3] $thisZip[3]"; 
    $thisAddress4 = "$thisAddress[4], $thisCity[4], $thisState[4] $thisZip[4]"; 
    $thisAddress5 = "$thisAddress[5], $thisCity[5], $thisState[5] $thisZip[5]"; 
    $thisAddress6 = "$thisAddress[6], $thisCity[6], $thisState[6] $thisZip[6]"; 
    $thisAddress7 = "$thisAddress[7], $thisCity[7], $thisState[7] $thisZip[7]"; 
    $thisAddress8 = "$thisAddress[8], $thisCity[8], $thisState[8] $thisZip[8]"; 
    $thisAddress9 = "$thisAddress[9], $thisCity[9], $thisState[9] $thisZip[9]"; 
    $thisAddress10 = "$thisAddress[10], $thisCity[10], $thisState[10] $thisZip[10]"; 
    $thisAddress11 = "$thisAddress[11], $thisCity[11], $thisState[11] $thisZip[11]"; 
    $thisAddress12 = "$thisAddress[12], $thisCity[12], $thisState[12] $thisZip[12]"; 
    $thisAddress13 = "$thisAddress[13], $thisCity[13], $thisState[13] $thisZip[13]"; 
    $thisAddress14 = "$thisAddress[14], $thisCity[14], $thisState[14] $thisZip[14]"; 
    $thisAddress15 = "$thisAddress[15], $thisCity[15], $thisState[15] $thisZip[15]"; 
    $thisAddress16 = "$thisAddress[16], $thisCity[16], $thisState[16] $thisZip[16]"; 
    $thisAddress17 = "$thisAddress[17], $thisCity[17], $thisState[17] $thisZip[17]"; 
    $thisAddress18 = "$thisAddress[18], $thisCity[18], $thisState[18] $thisZip[18]"; 
    $thisAddress19 = "$thisAddress[19], $thisCity[19], $thisState[19] $thisZip[19]"; 
    ?>
    

    Google Map Script:

    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YourKeyHere"  type="text/javascript"></script>
    
    <script type="text/javascript">
    if (GBrowserIsCompatible()) { 
    
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setUIToDefault();
    
        // Create a base icon for all of our markers that specifies the
        // shadow, icon dimensions, etc.
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
    
        // Creates a marker whose info window displays the letter corresponding
        // to the given index.
        function createMarker(point, index) {
          // Create a lettered icon for this point using our icon class
          var letter = String.fromCharCode("A".charCodeAt(0) + index);
          var letteredIcon = new GIcon(baseIcon);
          letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
    
          // Set up our GMarkerOptions object
          markerOptions = { icon:letteredIcon };
          var marker = new GMarker(point, markerOptions);
    
          GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(addresses[index]);
          });
          return marker;
        }
    
    
      // ====== Create a Client Geocoder ======
      var geo = new GClientGeocoder(); 
    
      // ====== Array for decoding the failure codes ======
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      reasons[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";
    
      var j=0;
      // ====== Geocoding ======
      function getAddress(search, next) {
        geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // Lets assume that the first marker is the one we want
              var p = result.Placemark[0].Point.coordinates;
              var lat=p[1];
              var lng=p[0];
              if(j == 0)
              {
                map.setCenter(new GLatLng(lat, lng), 15);
              }
    
                var latlng = new GLatLng(lat, lng);
                map.addOverlay(createMarker(latlng, j));
    
            }
            j++;
            next();
          }
        );
      }
    
    
      // ======= An array of locations that we want to Geocode ========
    addresses =   [
            "<?php echo $thisAddress0; ?>",
            "<?php echo $thisAddress1; ?>",
            "<?php echo $thisAddress2; ?>",
            "<?php echo $thisAddress3; ?>",
            "<?php echo $thisAddress4; ?>",
            "<?php echo $thisAddress5; ?>",
            "<?php echo $thisAddress6; ?>",
            "<?php echo $thisAddress7; ?>",
            "<?php echo $thisAddress8; ?>",
            "<?php echo $thisAddress9; ?>",
            "<?php echo $thisAddress10; ?>",
            "<?php echo $thisAddress11; ?>",
            "<?php echo $thisAddress12; ?>",
            "<?php echo $thisAddress13; ?>",
            "<?php echo $thisAddress14; ?>",
            "<?php echo $thisAddress15; ?>",
            "<?php echo $thisAddress16; ?>",
            "<?php echo $thisAddress17; ?>",
            "<?php echo $thisAddress18; ?>",
            "<?php echo $thisAddress19; ?>",
            ];
    
      // ======= Global variable to remind us what to do next
      var nextAddress = 0;
    
      // ======= Function to call the next Geocode operation when the reply comes back
    
      function theNext() {
        if (nextAddress < addresses.length) {
          getAddress(addresses[nextAddress],theNext);
          nextAddress++;
        }
      }
    
      // ======= Call that function for the first time =======
      theNext();
    
    }
    
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
    
    </script>