javascript - 如何使用 Google Maps API V3 制作显示边界的简单邮政编码 map ?

标签 javascript google-maps-api-3

我需要显示一个交互式 map ,其中邮政编码显示了它们的边界,并且邮政编码有不同的颜色,如下所示:

http://www.usnaviguide.com/zip.htm

输入美国邮政编码并单击“查找邮政编码”。

也许我忽略了它,但我一直没有在 Google Maps API 文档中找到这方面的示例和专门讨论此内容的文档。我正在尝试在上面的网页链接上查看源代码,但对我来说它是如何工作的似乎并不明显。页面上还有其他内容,我不知道它是否是我需要的部分。

一些简单的代码示例会很有帮助!谢谢!

最佳答案

这是我用 FusionTablesLayers 放在一起的美国邮政编码 map :

http://www.geocodezip.com/geoxml3_test/v3_FusionTables_zipcode_map.html

它没有不同的颜色,但您可以更改它。

John Coryat 使用图 block 服务器制作了该 map ,您可以使用 Google Maps API v3 自定义 map 执行相同的操作。

示例代码片段:

google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
var map;
var labels = [];
var layer;
var tableid =  1499916;

function initialize() {
    geocoder = new google.maps.Geocoder();
  	map = new google.maps.Map(document.getElementById('map_canvas'), {
    center: new google.maps.LatLng(37.23032838760389, -118.65234375),
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  
  layer = new google.maps.FusionTablesLayer(tableid);
  layer.setQuery("SELECT 'geometry' FROM " + tableid);
  layer.setMap(map);

  codeAddress("11501" /*document.getElementById("address").value*/ );

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

function codeAddress(address) {
    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({
            map: map, 
            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 displayZips() {
  //set the query using the current bounds
  var queryStr = "SELECT geometry, ZIP, latitude, longitude 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);
  // alert(queryStr);

  //set the callback function
  query.send(displayZipText);

}
 

  var infowindow = new google.maps.InfoWindow();
		
function displayZipText(response) {
if (!response) {
  alert('no response');
  return;
}
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
} 
  if (map.getZoom() < 11) return;
  FTresponse = response;
  //for more information on the response object, see the documentation
  //http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();
/*  var queryStr = "SELECT geometry, ZIP, latitude, longitude FROM "+ tableid + " WHERE ST_INTERSECTS(geometry, RECTANGLE(LATLNG"+map.getBounds().getSouthWest()+",LATLNG"+map.getBounds().getNorthEast()+"))";   
*/

  for(i = 0; i < numRows; i++) {
      var zip = response.getDataTable().getValue(i, 1);
      var zipStr = zip.toString()
      while (zipStr.length < 5) { zipStr = '0' + zipStr; }
      var point = new google.maps.LatLng(
          parseFloat(response.getDataTable().getValue(i, 2)),
          parseFloat(response.getDataTable().getValue(i, 3)));
      // bounds.extend(point);
      labels.push(new InfoBox({
	 content: zipStr
	,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);
  }
  // zoom to the bounds
  // map.fitBounds(bounds);
}

google.maps.event.addDomListener(window,'load',initialize);
#map_canvas { width: 610px; height: 400px; }
<script type="text/javascript" src="http://www.google.com/jsapi"></script>         
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></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://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>


<form> 
 	    <span class="style51"><span class="style49">Show</span>:</span> 
<input id="address" type="text" value="11501" ></input>
<input id="geocode" type="button" onclick="codeAddress(document.getElementById('address').value);" value="Geocode"></input>	  
<div id="map_canvas"></div>

关于javascript - 如何使用 Google Maps API V3 制作显示边界的简单邮政编码 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12782034/

相关文章:

javascript - Vue 使用 vuex 从另一个组件控制和更新状态

google-maps - API 用于显示距 Google map View 中的长/纬度位置最近的照片(如 Panoramio)

javascript - 将事件监听器应用于可编辑多边形

google-maps-api-3 - 光标在 Google map 应用程序中消失

google-maps - 如何访问 Google Maps API v3 标记的 DIV 及其像素位置?

javascript - 我想将图像加载到 "wave"..

javascript - 标识符 'reducer' 已声明

javascript - 在 native 钩子(Hook)之前加载可安装的钩子(Hook)

javascript - 如何在 HTML 中使用外部 Javascript 文件中的函数?

google-maps - 如何使用Flutter获取真实的方向指示? (绘制真实路线)