0

我有改进代码的问题。我基于 geocodezip 示例http://www.geocodezip.com/geoxml3_test//v3_FusionTables_CountryBrowser_encryptedID.html制作地图,现在我想在此代码库中集成标签也基于 geocodezip 示例http://www.geocodezip.com /geoxml3_test/v3_FusionTables_zipcode_map.html。当我独立使用标签代码时,此代码工作正常,但当我尝试将此代码与“FusionTables_CountryBrowser”代码集成时,标签名称未显示在地图上。有没有人有任何建议,我的集成代码有什么问题。

<!DOCTYPE html>
<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>USA8</title>

<style type="text/css">
html, body, #map_canvas {
    width:   750px;
    height:  600px;
    margin:  0;
    padding: 0;
}
.infowindow * {font-size: 90%; margin: 0}
.style1 {color: #FFFFFF}
</style>

<script type="text/javascript" src="http://www.google.com/jsapi"></script> 
<script type="text/javascript" src="https://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript" src="http://www.google-analytics.com/urchin.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>

<script type="text/javascript"> 
var map = null;
var infoWindow = null;
var geoXml = null;
var geoXmlDoc = null;
var myLatLng = null;
var myOptions = null;
var mapCenter = null;
var geocodeTheCountry = true;
var gpolygons = [];
var geocoder = null;
var geocoder2 = null;
var labels = [];
var layer;
var tableid = '1GoqHJ9E9Ff_rfl_CLTGNlgXF3ssEaywN4_lVNUA'; 
var CountryName = "USA"; 

google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});

function  createSidebar() {
// set the query using the parameters
document.getElementById('sidebar').innerHTML = "querying for data";
var FT_Query2 = "SELECT 'STATEFP', 'name', 'geometry' FROM "+tableid+" WHERE 'STATEFP' = '"+CountryName+"' ORDER by 'name'";
document.getElementById("FTquery2").innerHTML = FT_Query2; 
  var queryText = encodeURIComponent(FT_Query2);
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);
  //set the callback function
  query.send(getData);
}

  // Set a callback to run when the Google Visualization API is loaded.
  google.setOnLoadCallback(createSidebar);

function getCountryNames() {
  // set the query using the parameters
var FT_Query_CountryName = "SELECT 'STATEFP', count() FROM "+tableid+" GROUP by 'STATEFP' ORDER by 'STATEFP'";
document.getElementById("FTquery4").innerHTML = FT_Query_CountryName; 
  var queryText = encodeURIComponent(FT_Query_CountryName);
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);

  //set the callback function
  query.send(createCountryDropdown);
}

function createCountryDropdown(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();

  var countryNames = {};
  for (var i = 0; i < numRows; i++) {
    var countryName = response.getDataTable().getValue(i,0);
    countryNames[countryName] = countryName;
  }
  var countryNameDropdown = "<select name='country_select' onchange='handleSelected(this)'>"
  countryNameDropdown += '<option selected> - Select a State by ID - <\/option>';
  for (countryName in countryNames) {
    countryNameDropdown += "<option value='"+countryName+"'>"+countryName+"</option>"
  }
  countryNameDropdown += "</select>"
  document.getElementById('dropdown_menu').innerHTML = countryNameDropdown;
}

      // ======= This function handles selections from the select box ====
      function handleSelected(opt) {
        if (opt.selectedIndex > 0) {
          CountryName = geoXML3.nodeValue(opt[opt.selectedIndex]);
          DisplayCountry();
        } else { 
          alert("Please pick a country");
        }
      }

function DisplayCountry() {
      // geocode the country
      var addressStr = CountryName;
      if (addressStr != "Baikonur Cosmodrome") addressStr += " Country";
      geocoder.geocode( { 'address': addressStr}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);
          map.fitBounds(results[0].geometry.viewport);
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
   FT_Query = "SELECT 'geometry' FROM "+tableid+" WHERE 'STATEFP' = '"+CountryName+"';";
   gpolygons = [];
   layer.setQuery({select:'geometry',from:tableid,where:"'STATEFP' = '"+CountryName+"'"});
   document.getElementById("FTquery").innerHTML = FT_Query; 
   createSidebar();
}
</script>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
var FTresponse = null;
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
      myLatLng = new google.maps.LatLng(37.422104808,-122.0838851);
      var lat = 37.422104808;
      var lng = -122.0838851;
      var zoom = 18;
      var maptype = google.maps.MapTypeId.ROADMAP;
      var query = location.search.substring(1);
      var pairs = query.split("&");
      for (var i=0; i<pairs.length; i++) {  
    var pos = pairs[i].indexOf("=");
    var argname = pairs[i].substring(0,pos).toLowerCase();
    var value = pairs[i].substring(pos+1);
        if (argname == "country") {CountryName = unescape(value);}
    value = pairs[i].substring(pos+1).toLowerCase();
    if (argname == "geocode") {geocodeTheCountry = (value != "false");}
        if (argname == "id") {id = unescape(value);}
        if (argname == "filename") {filename = unescape(value);}
        if (argname == "marker") {index = parseFloat(value);}
        if (argname == "lat") {lat = parseFloat(value);}
        if (argname == "lng") {lng = parseFloat(value);}
        if (argname == "zoom") {
      zoom = parseInt(value);
      myGeoXml3Zoom = false;
    }
        if (argname == "type") {
          if (value == "m") {maptype = google.maps.MapTypeId.ROADMAP;}
          if (value == "k") {maptype = google.maps.MapTypeId.SATELLITE;}
          if (value == "h") {maptype = google.maps.MapTypeId.HYBRID;}
          if (value == "t") {maptype = google.maps.MapTypeId.TERRAIN;}
        }
      }
      if (!isNaN(lat) && !isNaN(lng)) {
        myLatLng = new google.maps.LatLng(lat, lng);
      }
      infoWindow = new google.maps.InfoWindow();

//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  FTresponse = response;
  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();
  if (numRows <= 1) {
    document.getElementById('sidebar').innerHTML = "no data";
    return;
  }

  //concatenate the results into a string, you can build a table here
  fusiontabledata = "<table><tr>";
  fusiontabledata += "<th colspan='2'>" + response.getDataTable().getValue(1,0) + "</th>";
  fusiontabledata += "</tr><tr>";
  fusiontabledata += "<tr><td colspan='2' align='left'><a href='javascript:showAll();'>Display all polygons in selected State</a></td></tr>";
  for(i = 0; i < numRows; i++) {

    fusiontabledata += "<td><a href='javascript:myFTclick("+i+")'>"+response.getDataTable().getValue(i, 1) + "</a></td><td><a href='javascript:zoomTo("+i+")' >show</a></td>";
    fusiontabledata += "</tr><tr>";
  }
  fusiontabledata += "</table>"  
  //display the results on the page
  document.getElementById('sidebar').innerHTML = fusiontabledata;
}

function infoWindowContent(name, description, id) {
   content =   '<div class="FT_infowindow"><h3>' + name + 
               '</h3><div>' + description + '</div>';
   if (typeof id != "undefined") {
     content += '<a href="javascript:zoomTo('+id+');">zoom to</a>';
   }
   content += '</div>';
   return content;
}

function zoomTo(id) {
  loadRow(id);
  if (gpolygons[id] && gpolygons[id].bounds) {
    map.fitBounds(gpolygons[id].bounds);
    var queryStr = "SELECT 'geometry' FROM "+tableid+" WHERE 'STATEFP' = '"+CountryName+"' AND 'name' = '"+gpolygons[id].name+"';"
    layer.setQuery({select:'geometry',from:tableid,where:"'STATEFP' = '"+CountryName+"' AND 'name' = '"+gpolygons[id].name+"'"});    
    document.getElementById("FTquery3").innerHTML = queryStr; 
  }
}

function showAll() {
  layer.setQuery({select: 'geometry', from:tableid, where:"'STATEFP' = '"+CountryName+"'"});
}

function loadRow(row) {
   if (!gpolygons[row]) {
     var name = FTresponse.getDataTable().getValue(row,1);
     var kml =  FTresponse.getDataTable().getValue(row,2);
     // create a geoXml3 parser for the click handlers
     var geoXml = new geoXML3.parser({
                    map: map,
            zoom: false,
                    infoWindow: infoWindow,
                    singleInfoWindow: true
                });
     geoXml.parseKmlString("<Placemark>"+kml+"</Placemark>");
     geoXml.docs[0].gpolygons[0].setMap(null);
     gpolygons[row] = new Object();
     gpolygons[row].position = geoXml.docs[0].gpolygons[0].bounds.getCenter();
     gpolygons[row].bounds = geoXml.docs[0].gpolygons[0].bounds;
     gpolygons[row].name = name;
   }
}
function myFTclick(row) {
   var description = FTresponse.getDataTable().getValue(row,0);
   var name = FTresponse.getDataTable().getValue(row,1);
   loadRow(row);
   var position = gpolygons[row].position;

   // Set up and create the infowindow
   if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
   infoWindow.setOptions({
      content: infoWindowContent(name, description, row),
      pixelOffset: new google.maps.Size(0, 2),
      position: position
    });
    // Infowindow-opening event handler
    infoWindow.open(map);
}

function initialize() {
  map = new google.maps.Map(document.getElementById("map_canvas"));

  google.maps.event.addListener(map, "click", function(event) {
    infoWindow.close();
    var FT_click_query="SELECT 'STATEFP' FROM "+tableid+" WHERE ST_INTERSECTS('geometry',CIRCLE(LATLNG"+event.latLng+", 1));";
    var queryText = encodeURIComponent(FT_click_query);
    var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);
    document.getElementById("FTquery5").innerHTML = FT_click_query; 

    //set the callback function
    query.send(getCountryFromClick);
  });

  geocoder = new google.maps.Geocoder();
  if (geocoder && geocodeTheCountry) {
    geocoder.geocode( { 'address': CountryName+" Country"}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);
          map.fitBounds(results[0].geometry.viewport);
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }


  layer = new google.maps.FusionTablesLayer();
  var countylayerOptions = {
  suppressInfoWindows: true,
  query: {
          select: 'geometry',
          from: '1GoqHJ9E9Ff_rfl_CLTGNlgXF3ssEaywN4_lVNUA'
         }
       }

  layer.setOptions(countylayerOptions);
  layer.setMap(map);

  google.maps.event.addListener(layer, "click", function(event) {
    infoWindow.close();
    infoWindow.setContent(infoWindowContent(event.row.name.value,event.row.STATEFP.value));
    infoWindow.setPosition(event.latLng);
    infoWindow.open(map);
  });

  getCountryNames();


//***labels***  
  createMarkerforLabels();
  google.maps.event.addListener(map, "idle", function() {
    displaynames();
  });

  google.maps.event.addListener(map, "zoom_changed", function() {
    if (map.getZoom() < 9) {
      for (var i=0; i<labels.length; i++) {
        labels[i].setMap(null);
      }
    }
  });
//***labels***


}

function getCountryFromClick(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();
  if (numRows <= 1) {
    return;
  }

  CountryName = response.getDataTable().getValue(1, 0);
  DisplayCountry();  


//***labels***
function createMarkerforLabels() {
    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            position: results[0].geometry.location
        });
        if (results[0].geometry.viewport) 
          map.fitBounds(results[0].geometry.viewport);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

function displaynames() {
  //set the query using the current bounds
  var queryStr = "SELECT geometry, name, INTPTLAT, INTPTLON FROM "+ tableid + " WHERE ST_INTERSECTS(geometry, RECTANGLE(LATLNG"+map.getBounds().getSouthWest()+",LATLNG"+map.getBounds().getNorthEast()+"))";   
  var queryText = encodeURIComponent(queryStr);
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);

  //set the callback function
  query.send(displaynameText);
}

var infowindow = new google.maps.InfoWindow();

function displaynameText(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  if (map.getZoom() < 9) return;
  FTresponse = response;

  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();

  for(i = 0; i < numRows; i++) {
      var name = response.getDataTable().getValue(i, 1);
      var nameStr = name.toString()
      while (nameStr.length < 5) { nameStr = '0' + nameStr; }
      var point = new google.maps.LatLng(
          parseFloat(response.getDataTable().getValue(i, 2)),
          parseFloat(response.getDataTable().getValue(i, 3)));

      labels.push(new InfoBox({
      content: nameStr
      ,boxStyle: {
         border: "1px solid black"
        ,textAlign: "center"
        ,backgroundColor:"white"
        ,fontSize: "8pt"
        ,width: "50px"
     }
      ,disableAutoPan: true
      ,pixelOffset: new google.maps.Size(-25, 0)
      ,position: point
      ,closeBoxURL: ""
      ,isHidden: false
      ,enableEventPropagation: true
      }));
      labels[labels.length-1].open(map);
  }
}
//***labels***


}    

</script>
</head>
<body onload="initialize()">
<div id="panel" style="position:absolute; left:50%; top:0px; width:900px; height:30px; z-index:2; margin-left: -450px; visibility: hidden;"><input id="address" type="text" value="USA" ></input></div>
<table style="width:100%;">
<tr><td colspan="2"><h4>USA States ID<div id="dropdown_menu">
</div></h4></td></tr>
<tr>
 <td><div id="map_canvas" style="border-style:solid; border-width:1px; border-color:#333333"></div></td>
 <td><div id="sidebar" style="width:300px;height:600px; border-style:solid; border-width:1px; border-color:#333333; overflow:auto"></div></td>
</tr>
<tr><td colspan="2"><span class="style1"><div id="FTquery"></div></td></tr>
<tr><td colspan="2"><span class="style1"><div id="FTquery2"></div></td></tr>
<tr><td colspan="2"><span class="style1"></td></tr>
<tr><td colspan="2"><span class="style1"><div id="FTquery4"></div></td></tr>
<tr><td colspan="2"><span class="style1"><div id="FTquery5"></div></td></tr>
</table>
<div id="country_list"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script> 
<script type="text/javascript"> _uacct = "UA-162157-1"; urchinTracker();</script> 
</body>
</html>
4

1 回答 1

0

感谢 geocodezip,你是对的,问题是未定义的 JavaScript 变量。抱歉,我忘记从代码中删除您的谷歌分析,现在已删除。工作的代码如下所示。

<!DOCTYPE html>
<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>USA8</title>

<style type="text/css">
html, body, #map_canvas {
    width:   750px;
    height:  600px;
    margin:  0;
    padding: 0;
}
.infowindow * {font-size: 90%; margin: 0}
.style1 {color: #FFFFFF}
</style>

<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script> 
<script type="text/javascript" src="https://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>

<script type="text/javascript"> 
var map = null;
var infoWindow = null;
var geoXml = null;
var geoXmlDoc = null;
var myLatLng = null;
var myOptions = null;
var mapCenter = null;
var geocodeTheCountry = true;
var gpolygons = [];
var geocoder = null;
var FT_TableID = '1GoqHJ9E9Ff_rfl_CLTGNlgXF3ssEaywN4_lVNUA'; 
var CountryName = "USA"; 

  google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});

function  createSidebar() {
// set the query using the parameters
document.getElementById('sidebar').innerHTML = "querying for data";
var FT_Query2 = "SELECT 'STATEFP', 'name', 'geometry' FROM "+tableid+" WHERE 'STATEFP' = '"+CountryName+"' ORDER by 'name'";
document.getElementById("FTquery2").innerHTML = FT_Query2; 
  var queryText = encodeURIComponent(FT_Query2);
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);
  //set the callback function
  query.send(getData);
}

  // Set a callback to run when the Google Visualization API is loaded.
  google.setOnLoadCallback(createSidebar);

function getCountryNames() {
  // set the query using the parameters
var FT_Query_CountryName = "SELECT 'STATEFP', count() FROM "+tableid+" GROUP by 'STATEFP' ORDER by 'STATEFP'";
document.getElementById("FTquery4").innerHTML = FT_Query_CountryName; 
  var queryText = encodeURIComponent(FT_Query_CountryName);
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);

  //set the callback function
  query.send(createCountryDropdown);
}

function createCountryDropdown(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();

  var countryNames = {};
  for (var i = 0; i < numRows; i++) {
    var countryName = response.getDataTable().getValue(i,0);
    countryNames[countryName] = countryName;
  }
  var countryNameDropdown = "<select name='country_select' onchange='handleSelected(this)'>"
  countryNameDropdown += '<option selected> - Select a State by ID - <\/option>';
  for (countryName in countryNames) {
    countryNameDropdown += "<option value='"+countryName+"'>"+countryName+"</option>"
  }
  countryNameDropdown += "</select>"
  document.getElementById('dropdown_menu').innerHTML = countryNameDropdown;
}

      // ======= This function handles selections from the select box ====
      function handleSelected(opt) {
        if (opt.selectedIndex > 0) {
          CountryName = geoXML3.nodeValue(opt[opt.selectedIndex]);
          DisplayCountry();
        } else { 
          alert("Please pick a country");
        }
      }

function DisplayCountry() {
      // geocode the country
      var addressStr = CountryName;
      if (addressStr != "Baikonur Cosmodrome") addressStr += " Country";
      geocoder.geocode( { 'address': addressStr}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);
          map.fitBounds(results[0].geometry.viewport);
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
   FT_Query = "SELECT 'geometry' FROM "+tableid+" WHERE 'STATEFP' = '"+CountryName+"';";
   gpolygons = [];
   layer.setQuery({select:'geometry',from:tableid,where:"'STATEFP' = '"+CountryName+"'"});
   document.getElementById("FTquery").innerHTML = FT_Query; 
   createSidebar();
}
</script>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript" src="http://www.google-analytics.com/urchin.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>

<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
var FTresponse = null;
var map;
var labels = [];
var layer;
var tableid = '1GoqHJ9E9Ff_rfl_CLTGNlgXF3ssEaywN4_lVNUA'; 

      myLatLng = new google.maps.LatLng(37.422104808,-122.0838851);
      var lat = 37.422104808;
      var lng = -122.0838851;
      var zoom = 18;
      var maptype = google.maps.MapTypeId.ROADMAP;
      var query = location.search.substring(1);
      var pairs = query.split("&");
      for (var i=0; i<pairs.length; i++) {  
    var pos = pairs[i].indexOf("=");
    var argname = pairs[i].substring(0,pos).toLowerCase();
    var value = pairs[i].substring(pos+1);
        if (argname == "country") {CountryName = unescape(value);}
    value = pairs[i].substring(pos+1).toLowerCase();
    if (argname == "geocode") {geocodeTheCountry = (value != "false");}
        if (argname == "id") {id = unescape(value);}
        if (argname == "filename") {filename = unescape(value);}
        if (argname == "marker") {index = parseFloat(value);}
        if (argname == "lat") {lat = parseFloat(value);}
        if (argname == "lng") {lng = parseFloat(value);}
        if (argname == "zoom") {
      zoom = parseInt(value);
      myGeoXml3Zoom = false;
    }
        if (argname == "type") {
          if (value == "m") {maptype = google.maps.MapTypeId.ROADMAP;}
          if (value == "k") {maptype = google.maps.MapTypeId.SATELLITE;}
          if (value == "h") {maptype = google.maps.MapTypeId.HYBRID;}
          if (value == "t") {maptype = google.maps.MapTypeId.TERRAIN;}
        }
      }
      if (!isNaN(lat) && !isNaN(lng)) {
        myLatLng = new google.maps.LatLng(lat, lng);
      }
      infoWindow = new google.maps.InfoWindow();

//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  FTresponse = response;
  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();
  if (numRows <= 1) {
    document.getElementById('sidebar').innerHTML = "no data";
    return;
  }

  //concatenate the results into a string, you can build a table here
  fusiontabledata = "<table><tr>";
  fusiontabledata += "<th colspan='2'>" + response.getDataTable().getValue(1,0) + "</th>";
  fusiontabledata += "</tr><tr>";
  fusiontabledata += "<tr><td colspan='2' align='left'><a href='javascript:showAll();'>Display all polygons in selected State</a></td></tr>";
  for(i = 0; i < numRows; i++) {

    fusiontabledata += "<td><a href='javascript:myFTclick("+i+")'>"+response.getDataTable().getValue(i, 1) + "</a></td><td><a href='javascript:zoomTo("+i+")' >show</a></td>";
    fusiontabledata += "</tr><tr>";
  }
  fusiontabledata += "</table>"  
  //display the results on the page
  document.getElementById('sidebar').innerHTML = fusiontabledata;
}

function infoWindowContent(name, description, id) {
   content =   '<div class="FT_infowindow"><h3>' + name + 
               '</h3><div>' + description + '</div>';
   if (typeof id != "undefined") {
     content += '<a href="javascript:zoomTo('+id+');">zoom to</a>';
   }
   content += '</div>';
   return content;
}

function zoomTo(id) {
  loadRow(id);
  if (gpolygons[id] && gpolygons[id].bounds) {
    map.fitBounds(gpolygons[id].bounds);
    var queryStr = "SELECT 'geometry' FROM "+tableid+" WHERE 'STATEFP' = '"+CountryName+"' AND 'name' = '"+gpolygons[id].name+"';"
    layer.setQuery({select:'geometry',from:tableid,where:"'STATEFP' = '"+CountryName+"' AND 'name' = '"+gpolygons[id].name+"'"});    
    document.getElementById("FTquery3").innerHTML = queryStr; 
  }
}

function showAll() {
  layer.setQuery({select: 'geometry', from:tableid, where:"'STATEFP' = '"+CountryName+"'"});
}

function loadRow(row) {
   if (!gpolygons[row]) {
     var name = FTresponse.getDataTable().getValue(row,1);
     var kml =  FTresponse.getDataTable().getValue(row,2);
     // create a geoXml3 parser for the click handlers
     var geoXml = new geoXML3.parser({
                    map: map,
            zoom: false,
                    infoWindow: infoWindow,
                    singleInfoWindow: true
                });
     geoXml.parseKmlString("<Placemark>"+kml+"</Placemark>");
     geoXml.docs[0].gpolygons[0].setMap(null);
     gpolygons[row] = new Object();
     gpolygons[row].position = geoXml.docs[0].gpolygons[0].bounds.getCenter();
     gpolygons[row].bounds = geoXml.docs[0].gpolygons[0].bounds;
     gpolygons[row].name = name;
   }
}
function myFTclick(row) {
   var description = FTresponse.getDataTable().getValue(row,0);
   var name = FTresponse.getDataTable().getValue(row,1);
   loadRow(row);
   var position = gpolygons[row].position;

   // Set up and create the infowindow
   if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
   infoWindow.setOptions({
      content: infoWindowContent(name, description, row),
      pixelOffset: new google.maps.Size(0, 2),
      position: position
    });
    // Infowindow-opening event handler
    infoWindow.open(map);
}

function initialize() {
  map = new google.maps.Map(document.getElementById("map_canvas"));

  google.maps.event.addListener(map, "click", function(event) {
    infoWindow.close();
    var FT_click_query="SELECT 'STATEFP' FROM "+tableid+" WHERE ST_INTERSECTS('geometry',CIRCLE(LATLNG"+event.latLng+", 1));";
    var queryText = encodeURIComponent(FT_click_query);
    var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);
    document.getElementById("FTquery5").innerHTML = FT_click_query; 

    //set the callback function
    query.send(getCountryFromClick);
  });

  geocoder = new google.maps.Geocoder();
  if (geocoder && geocodeTheCountry) {
    geocoder.geocode( { 'address': CountryName+" Country"}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);
          map.fitBounds(results[0].geometry.viewport);
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }

  layer = new google.maps.FusionTablesLayer();
  var countylayerOptions = {
  suppressInfoWindows: true,
  query: {
          select: 'geometry',
          from: '1GoqHJ9E9Ff_rfl_CLTGNlgXF3ssEaywN4_lVNUA'
         }
       }

  layer.setOptions(countylayerOptions);
  layer.setMap(map);

  google.maps.event.addListener(layer, "click", function(event) {
    infoWindow.close();
    infoWindow.setContent(infoWindowContent(event.row.name.value,event.row.STATEFP.value));
    infoWindow.setPosition(event.latLng);
    infoWindow.open(map);
  });

  getCountryNames();


//***labels***  
  createMarkerforLabels();
  google.maps.event.addListener(map, "idle", function() {
    displaynames();
  });

  google.maps.event.addListener(map, "zoom_changed", function() {
    if (map.getZoom() < 9) {
      for (var i=0; i<labels.length; i++) {
        labels[i].setMap(null);
      }
    }
  });
}

function createMarkerforLabels() {
    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            position: results[0].geometry.location
        });
        if (results[0].geometry.viewport) 
          map.fitBounds(results[0].geometry.viewport);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

function displaynames() {
  //set the query using the current bounds
  var queryStr = "SELECT geometry, name, INTPTLAT, INTPTLON FROM "+ tableid + " WHERE ST_INTERSECTS(geometry, RECTANGLE(LATLNG"+map.getBounds().getSouthWest()+",LATLNG"+map.getBounds().getNorthEast()+"))";   
  var queryText = encodeURIComponent(queryStr);
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);

  //set the callback function
  query.send(displaynameText);
}

var infowindow = new google.maps.InfoWindow();

function displaynameText(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  if (map.getZoom() < 9) return;
  FTresponse = response;

  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();

  for(i = 0; i < numRows; i++) {
      var name = response.getDataTable().getValue(i, 1);
      var nameStr = name.toString()
      while (nameStr.length < 5) { nameStr = '0' + nameStr; }
      var point = new google.maps.LatLng(
          parseFloat(response.getDataTable().getValue(i, 2)),
          parseFloat(response.getDataTable().getValue(i, 3)));

      labels.push(new InfoBox({
      content: nameStr
      ,boxStyle: {
         border: "1px solid black"
        ,textAlign: "center"
        ,backgroundColor:"white"
        ,fontSize: "8pt"
        ,width: "50px"
     }
      ,disableAutoPan: true
      ,pixelOffset: new google.maps.Size(-25, 0)
      ,position: point
      ,closeBoxURL: ""
      ,isHidden: false
      ,enableEventPropagation: true
      }));
      labels[labels.length-1].open(map);
  }
}

function getCountryFromClick(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();
  if (numRows <= 1) {
    return;
  }

  CountryName = response.getDataTable().getValue(1, 0);
  DisplayCountry();  
}

</script>
</head>
<body onload="initialize()">
<div id="panel" style="position:absolute; left:50%; top:0px; width:900px; height:30px; z-index:2; margin-left: -450px; visibility: hidden;"><input id="address" type="text" value="USA" ></input></div>
<table style="width:100%;">
<tr><td colspan="2"><h4>USA States ID<div id="dropdown_menu">
</div></h4></td></tr>
<tr>
 <td><div id="map_canvas" style="border-style:solid; border-width:1px; border-color:#333333"></div></td>
 <td><div id="sidebar" style="width:300px;height:600px; border-style:solid; border-width:1px; border-color:#333333; overflow:auto"></div></td>
</tr>
<tr><td colspan="2"><span class="style1"><div id="FTquery"></div></td></tr>
<tr><td colspan="2"><span class="style1"><div id="FTquery2"></div></td></tr>
<tr><td colspan="2"><span class="style1"></td></tr>
<tr><td colspan="2"><span class="style1"><div id="FTquery4"></div></td></tr>
<tr><td colspan="2"><span class="style1"><div id="FTquery5"></div></td></tr>
</table>
<div id="country_list"></div>

</body>
</html>
于 2013-08-27T12:29:33.823 回答