doushi2902
2012-04-19 20:36
浏览 88

Google Maps API:如何将源代码从Google Spreadsheet API替换为MySQL / PHP?

I know nothing about google maps >_< , and I was asked to update the source of this page

I need to replace the current source (access to this Google Spreadsheet API account is lost).

As I explained, I have no training on google maps. However, I figure that to replace the current source, creating a mysql/php array or something would be easy. However, I have no idea how to do it for google maps.

Here is the Google map's code:

<? $this->load->view("inc/header");
?>
  <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAALG0LY9VczfCgBGR3gYl-OhSYZ3oXbzqsmNbiZCTxCau3LOQmUxTyi2riEMwN4Qit7X7U2xmd_NND1w" 

  type="text/javascript"></script>

  <script type="text/javascript">

//<![CDATA[
var cm_map;
var cm_mapMarkers = [];
var cm_mapHTMLS = [];

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

// Change these parameters to customize map
var param_wsId = "od6";
var param_ssKey = "t63uNv1JYAjjbdSo2NVr0ew";
var param_useSidebar = true;
var param_titleColumn = "address";
var param_descriptionColumn = "link";
var param_latColumn = "latitude";
var param_lngColumn = "longitude";
var param_rankColumn = "";
var param_iconType = "red";
var param_iconOverType = "green";

/**
 * Loads map and calls function to load in worksheet data.
 */
function cm_load() {  
  if (GBrowserIsCompatible()) {
    // create the map
    cm_map = new GMap2(document.getElementById("cm_map"));
    cm_map.addControl(new GLargeMapControl());
    cm_map.addControl(new GMapTypeControl());
    cm_map.setCenter(new GLatLng( 43.907787,-79.359741), 2);
    cm_getJSON();
  } else {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  } 
}

/**
 * Function called when marker on the map is clicked.
 * Opens an info window (bubble) above the marker.
 * @param {Number} markerNum Number of marker in global array
 */
function cm_markerClicked(markerNum) {
  cm_mapMarkers[markerNum].openInfoWindowHtml(cm_mapHTMLS[markerNum]);
}

/**
 * Function that sorts 2 worksheet rows from JSON feed
 * based on their rank column. Only called if column is defined.
 * @param {rowA} Object Represents row in JSON feed
 * @param {rowB} Object Represents row in JSON feed
 * @return {Number} Difference between row values
 */
function cm_sortRows(rowA, rowB) {
  var rowAValue = parseFloat(rowA["gsx$" + param_rankColumn].$t);
  var rowBValue = parseFloat(rowB["gsx$" + param_rankColumn].$t);

  return rowAValue - rowBValue;
}

/** 
 * Called when JSON is loaded. Creates sidebar if param_sideBar is true.
 * Sorts rows if param_rankColumn is valid column. Iterates through worksheet rows, 
 * creating marker and sidebar entries for each row.
 * @param {JSON} json Worksheet feed
 */       
function cm_loadMapJSON(json) {
  var usingRank = false;

  if(param_useSidebar == true) {
    var sidebarTD = document.createElement("td");
    sidebarTD.setAttribute("width","150");
    sidebarTD.setAttribute("valign","top");
    var sidebarDIV = document.createElement("div");
    sidebarDIV.id = "cm_sidebarDIV";
    sidebarDIV.style.overflow = "auto";
    sidebarDIV.style.height = "860px";
    sidebarDIV.style.fontSize = "11px";
    sidebarDIV.style.color = "#000000";
    sidebarTD.appendChild(sidebarDIV);
    document.getElementById("cm_mapTR").appendChild(sidebarTD);
  }

  var bounds = new GLatLngBounds();   

  if(json.feed.entry[0]["gsx$" + param_rankColumn]) {
    usingRank = true;
    json.feed.entry.sort(cm_sortRows);
  }
  for (var i = 0; i < <?=count($address)+1?>; i++) {
    var entry = json.feed.entry[i];

    if(entry["gsx$" + param_latColumn]) {
      var lat = parseFloat(entry["gsx$" + param_latColumn].$t);
      var lng = parseFloat(entry["gsx$" + param_lngColumn].$t);
      var point = new GLatLng(lat,lng);
      var html = "<div style='font-size:12px'>";
      html += "<strong>" + entry["gsx$"+param_titleColumn].$t 
              + "</strong>";
      var label = entry["gsx$"+param_titleColumn].$t;
      var rank = 0;
      if(usingRank && entry["gsx$" + param_rankColumn]) {
        rank = parseInt(entry["gsx$"+param_rankColumn].$t);
      }
        var trimmed = label.replace(/^\s+|\s+$/g, '') ;
        var link_label = label.replace(/ /gi,'-');
        link_label = link_label.toLowerCase();
        link_label = link_label.replace(/^\s+|\s+$/g, '') ;

if(trimmed == "1286 West Adams Blvd" )
{
     if(entry["gsx$" + param_descriptionColumn]) {
    html += "<br/><a href=\"<?=base_url()?>Housing/propertyDetail/1286-west-adams-blvd.html\">Click here for housing option</a>" ;
    }

}
else if(trimmed == "1239 West 30th Street")
{
    if(entry["gsx$" + param_descriptionColumn]) {
    html += "<br/><a href=\"<?=base_url()?>Housing/propertyDetail/1352-west-29th-street.html\">Click here for housing option</a>" ;
    }
}

else if(trimmed == "2150 Oak Street")
{
    if(entry["gsx$" + param_descriptionColumn]) {
    html += "<br/><a href=\"<?=base_url()?>Housing/propertyDetail/2126-50-south-oak-867-889-west-23rd-street.html\">Click here for housing option</a>" ;
    }
}
else if(trimmed == "1146 West 36th Place")
{
    if(entry["gsx$" + param_descriptionColumn]) {
    html += "<br/><a href=\"<?=base_url()?>Housing/propertyDetail/1140--1168-west-36th-place.html\">Click here for housing option</a>" ;
    }
}else if(trimmed == "1199 West 37th Drive")
{
    if(entry["gsx$" + param_descriptionColumn]) {
    html += "<br/><a href=\"<?=base_url()?>Housing/propertyDetail/1189--1199-west-37th-drive.html\">Click here for housing option</a>" ;
    }
}
else if(trimmed == "2611 South Portland Street")
{
    if(entry["gsx$" + param_descriptionColumn]) {
    html += "<br/><a href=\"<?=base_url()?>Housing/propertyDetail/2611-south-portland.html\">Click here for housing option</a>" ;
    }
}

else
{
    if(entry["gsx$" + param_descriptionColumn]) {

        html += "<br/><a href=\"<?=base_url()?>Housing/propertyDetail/"+link_label+".html\">Click here for housing option</a>" ;
           }

}



      html += "</div>";



      // create the marker

      var marker = cm_createMarker(point,label,html,rank);
      //label = 'hello';
      cm_map.addOverlay(marker);

      cm_mapMarkers.push(marker);

      cm_mapHTMLS.push(html);

      bounds.extend(point);



      if(param_useSidebar == true) {

        var markerA = document.createElement("a");

        markerA.setAttribute("href","javascript:cm_markerClicked('" + i +"')");

        markerA.style.color = "#000000";

        var sidebarText= "";

        if(usingRank) {

          sidebarText += rank + ") ";

        } 

        sidebarText += label;

        markerA.appendChild(document.createTextNode(sidebarText));

        // condition to remove an address from the list....
        /*if(trimmed != '1155 24th Street')
        {*/
            sidebarDIV.appendChild(markerA);

            sidebarDIV.appendChild(document.createElement("br"));

            sidebarDIV.appendChild(document.createElement("br"));
        //}



      } 

    }

  }



  cm_map.setZoom(cm_map.getBoundsZoomLevel(bounds));

  cm_map.setCenter(bounds.getCenter());

}



/**

 * Creates marker with ranked Icon or blank icon,

 * depending if rank is defined. Assigns onclick function.

 * @param {GLatLng} point Point to create marker at

 * @param {String} title Tooltip title to display for marker

 * @param {String} html HTML to display in InfoWindow

 * @param {Number} rank Number rank of marker, used in creating icon

 * @return {GMarker} Marker created

 */

function cm_createMarker(point, title, html, rank) {

  var markerOpts = {};

  var nIcon = new GIcon(cm_baseIcon);



  if(rank > 0 && rank < 100) {

    nIcon.imageOut = "http://gmaps-samples.googlecode.com/svn/trunk/" +

        "markers/" + param_iconType + "/marker" + rank + ".png";

    nIcon.imageOver = "http://gmaps-samples.googlecode.com/svn/trunk/" +

        "markers/" + param_iconOverType + "/marker" + rank + ".png";

    nIcon.image = nIcon.imageOut; 

  } else { 

    nIcon.imageOut = "http://gmaps-samples.googlecode.com/svn/trunk/" +

        "markers/" + param_iconType + "/blank.png";

    nIcon.imageOver = "http://gmaps-samples.googlecode.com/svn/trunk/" +

        "markers/" + param_iconOverType + "/blank.png";

    nIcon.image = nIcon.imageOut;

  }



  markerOpts.icon = nIcon;

  markerOpts.title = title;      

  var marker = new GMarker(point, markerOpts);



  GEvent.addListener(marker, "click", function() {

    marker.openInfoWindowHtml(html);

  });

  GEvent.addListener(marker, "mouseover", function() {

    marker.setImage(marker.getIcon().imageOver);

  });

  GEvent.addListener(marker, "mouseout", function() {

    marker.setImage(marker.getIcon().imageOut);

  });

  GEvent.addListener(marker, "infowindowopen", function() {

    marker.setImage(marker.getIcon().imageOver);

  });

  GEvent.addListener(marker, "infowindowclose", function() {

    marker.setImage(marker.getIcon().imageOut);

  });

  return marker;

}



/**

 * Creates a script tag in the page that loads in the 

 * JSON feed for the specified key/ID. 

 * Once loaded, it calls cm_loadMapJSON.

 */

function cm_getJSON() {



  // Retrieve the JSON feed.

  var script = document.createElement('script');

  script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list'

                         + '/' + param_ssKey + '/' + param_wsId + '/public/values' +

                        '?alt=json-in-script&callback=cm_loadMapJSON');

  script.setAttribute('id', 'jsonScript');

  script.setAttribute('type', 'text/javascript');

  document.documentElement.firstChild.appendChild(script);
}



setTimeout('cm_load()', 500); 



//]]>



</script>
<body onLoad="FP_preloadImgs(/*url*/'button18.jpg', /*url*/'button19.jpg'); if (document.getElementById('zoom_searchbox')) {document.getElementById('zoom_searchbox').focus();}" bgcolor=#969696>
<div id="junaid"></div>
<div class="body_main">

<div class="banner_contianer">
                <div class="banner_bg"><img src="<?=base_url()?>banners/properties.png" alt="" /></div>
                <div class="banner_btm_flear"></div></div>


                <div class="body_left_cont">
                    <div class="welcome_message">
                        <h1><?=$page_data['heading']?></h1>
                  </div>
                        <div class="tabs_main_cont" >
                <div class="tabs_md_show"><img src="<?=base_url()?>images/search-top-bg.png" alt="" /></div>
                    <div class="tabs_data_cont">
                            <div class="tabs_repeat_inner">
                                <div class="show_detail_contianer">
                                    <div class="show_In_cont">
                                    <div class="show_In_properties">
                                        <table bgcolor="#FFFFFF" id="cm_mapTABLE"> 

      <tbody> <tr id="cm_mapTR">



          <td> <div id="cm_map" style="width:530px; height:860px"></div> </td>

      </tr> </tbody>

    </table>
                                       </div> 
                                    </div>
                                </div>
                            </div>
                           <div class="tabs_md_show"><img src="<?=base_url()?>images/search-btm-bg.png" alt="" /></div>           
              </div>

                    </div>

                        </div>

                </body>

                        <?PHP
//$this->load->view("inc/right_panel");
?>

                            <div class="opportunities">We Do Business In Accordance With The Federal Fair Housing Law Equal Housing Opportunity</div>
                </div>

        <?PHP
$this->load->view("inc/footer");
?>

If I have a mysql/php array, how do I replace the source?:

<?php
include('database.php');
while($data = mysql_fetch_array($DATABASE))
{
   $map_source['address'] = data['address'];
   $map_source['lat'] = data['long'];
   $map_source['long'] = data['lat'];
}
mysql_close($con);
?>

How do I echo the array to replace the source?




EDIT: 4/19/2012 4:30pm** After going through the tutorial @mano-marks provided, I was able to get almost everything together. However, this test page) is not showing anything. Can you please help me figure out what is wrong?

PHP/XML:

<?php
require("database.php");

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 tbl_address table
$query = "SELECT * FROM tbl_address WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . 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['g_address']) . '" ';
  echo 'address="' . parseToXML($row['g_address']) . '" ';
  echo 'lat="' . $row['g_latitude'] . '" ';
  echo 'lng="' . $row['g_longitude'] . '" ';
  echo 'type="USC Student Housing" ';
  echo '/>';
}

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

?>

HTML MAP:

<!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="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    //<![CDATA[
    var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      }
    };
    function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(47.6145, -122.3418),
        zoom: 13,
        mapTypeId: 'roadmap'
      });
      var infoWindow = new google.maps.InfoWindow;
      // Change this depending on the name of your PHP file
      downloadUrl("http://firstchoicehousing.com/_api/google/maps/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;
          var icon = customIcons[[]type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            shadow: icon.shadow
          });
          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="load()">
    <div id="map" style="width: 500px; height: 300px"></div>
  </body>
</html>**
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshi8359 2012-04-19 21:22
    已采纳

    So you have another problem you're not aware of, which is that you're using version 2 of the Google Maps API, which is deprecated, and could be shut off next year. Version 3 is the current version. There's a couple of articles on the Google Maps API developer site that use PHP/MySQL to get started with Google Maps API: https://developers.google.com/maps/articles/phpsqlajax_v3 https://developers.google.com/maps/articles/phpsqlsearch_v3

    点赞 打赏 评论

相关推荐 更多相似问题