画矩形示例

此示例展示如何在地图区绘制矩形对象。当地图区变化时,绘制一个覆盖全部地图区的矩形。

关键代码

    rectangle = new sogou.maps.Rectangle();
    sogou.maps.event.addListener(map, 'zoom_changed', function() {
      // 获取当前Bounds,重新绘制矩形
      var rectOptions = {
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        map: map,
        bounds: map.getBounds()
      };
      rectangle.setOptions(rectOptions);
    });

代码解析

创建一个空矩形对象。

    rectangle = new sogou.maps.Rectangle();

侦听地图区视野变化,设置矩形参数,绘制覆盖全部地图区域的矩形。

    sogou.maps.event.addListener(map, 'zoom_changed', function() {
      // 获取当前Bounds,重新绘制矩形
      var rectOptions = {
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        map: map,
        bounds: map.getBounds()
      };
      rectangle.setOptions(rectOptions);
    });

完整代码

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>搜狗地图 JavaScript API 示例:画矩形示例</title>
<style type="text/css">
html {height: auto;}
body {height: auto;margin: 0;padding: 0;}
#map_canvas {width:1000px;height: 500px;position: absolute;}
@media print {#map_canvas {height: 950px;}}
</style>
<script type="text/javascript" src="//api.go2map.com/maps/js/api_v2.5.1.js"></script>
<script type="text/javascript">
 /**
  * 画矩形示例
  * 缩放地图时,获取当前的地图范围,绘制矩形
  * 可以看到缩放地图时总是盖住一层红色半透明的层
  * 拖动一下地图才能看到这个矩形
  */
  function initialize() {
  
    var rectangle;
    var coachella = new sogou.maps.LatLng(39.992792,116.326142);

    var myOptions = {
      zoom: 11,
      center: coachella,
      mapTypeId: sogou.maps.MapTypeId.ROADMAP
    };

    var map = new sogou.maps.Map(document.getElementById("map_canvas"),
        myOptions);
        
    rectangle = new sogou.maps.Rectangle();

    sogou.maps.event.addListener(map, 'zoom_changed', function() {

      // 获取当前Bounds,重新绘制矩形
      var rectOptions = {
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        map: map,
        bounds: map.getBounds()
      };
      rectangle.setOptions(rectOptions);
    });
  }
</script>
</head>
<body onload="initialize()">
缩放地图,然后在拖动一下地图看看:
  <div id="map_canvas"></div>
</body>
</html>

运行代码