简单的事件示例

此示例展示对地图区和标记对象的事件侦听及标记对象侦听的删除。缩放视野会提示当前视野级数。点击标记会将地图视野缩放到8级。

点击上面的按键将取消对点击标记的侦听。视野不会再调整到8级。

关键代码

    //添加侦听器,当缩放地图时触发,弹出对话框
	sogou.maps.event.addListener(map, 'zoom_changed', function() {
      moveToDarwin()
    });

    var marker = new sogou.maps.Marker({
        position: myLatlng, 
        map: map, 
        title:"Hello World!"
    });

	//添加侦听器,当点击标记时触发,将地图缩放到第8级
    mapsEventListener=sogou.maps.event.addListener(marker, 'click', function() {
      map.setZoom(8);
    });

  //删除侦听器
  function removeEvent()
  {
	//删除侦听器后再点击标记,将不再响应
	sogou.maps.event.removeListener(mapsEventListener)
  }
			

代码解析

添加对地图区视野缩放的侦听

    //添加侦听器,当缩放地图时触发,弹出对话框
	sogou.maps.event.addListener(map, 'zoom_changed', function() {
      moveToDarwin()
    });

绘制一个地图标记,设置点击标记时的侦听

    var marker = new sogou.maps.Marker({
        position: myLatlng, 
        map: map, 
        title:"Hello World!"
    });
	//添加侦听器,当点击标记时触发,将地图缩放到第8级
    mapsEventListener=sogou.maps.event.addListener(marker, 'click', function() {
      map.setZoom(8);
    });

删除对标记的点击侦听

  //删除侦听器
  function removeEvent()
  {
	//删除侦听器后再点击标记,将不再响应
	sogou.maps.event.removeListener(mapsEventListener)
  }

完整代码

<!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">
 /**
  * 简单的事件示例
  * 缩放地图时的侦听器
  * 点击标记的侦听器
  */
  var map,mapsEventListener;
  function initialize() {
    var myLatlng = new sogou.maps.LatLng(39.992792,116.326142);
    var myOptions = {
      zoom: 12,
      center: myLatlng,
      mapTypeId: sogou.maps.MapTypeId.ROADMAP
    }
    map = new sogou.maps.Map(document.getElementById("map_canvas"), myOptions);

    //添加侦听器,当缩放地图时触发,弹出对话框
	sogou.maps.event.addListener(map, 'zoom_changed', function() {
      moveToDarwin()
    });

    var marker = new sogou.maps.Marker({
        position: myLatlng, 
        map: map, 
        title:"Hello World!"
    });
	//添加侦听器,当点击标记时触发,将地图缩放到第8级
    mapsEventListener=sogou.maps.event.addListener(marker, 'click', function() {
      map.setZoom(8);
    });
  }

  function moveToDarwin() {
    alert(map.getZoom())
  }
  //删除侦听器
  function removeEvent()
  {
	//删除侦听器后再点击标记,将不再响应
	sogou.maps.event.removeListener(mapsEventListener)
  }

</script>
</head>
<body onload="initialize()">
<input type="button" onclick="removeEvent()" value="removeEventListener()" />
  <div id="map_canvas"></div>
</body>
</html>

运行代码