事件以及事件参数示例

此示例展示对地图区的事件侦听并在事件位置绘制标志。点击地图,获取地图坐标,用坐标绘制标记,移动地图中心到坐标处。

关键代码

  sogou.maps.event.addListener(map, 'click', function(event) {
	//获取点击位置的坐标
	alert(event.point)
    placeMarker(event.point);
  });
  
function placeMarker(location) {
  var clickedLocation = location;
  var marker = new sogou.maps.Marker({
      position: location, 
      map: map
  });

  map.setCenter(location);
}

代码解析

添加对地图区点击的侦听。触发时弹出显示坐标信息,并调用标志绘制。

  sogou.maps.event.addListener(map, 'click', function(event) {
	//获取点击位置的坐标
	alert(event.point)
    placeMarker(event.point);
  });

根据传入的坐标信息绘制标志,并设置地图中心到坐标位置。

function placeMarker(location) {
  var clickedLocation = location;
  var marker = new sogou.maps.Marker({
      position: location, 
      map: map
  });
  map.setCenter(location);
}

完整代码

<!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;
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, 'click', function(event) {
	//获取点击位置的坐标
	alert(event.point)
    placeMarker(event.point);
  });
}
  
function placeMarker(location) {
  var clickedLocation = location;
  var marker = new sogou.maps.Marker({
      position: location, 
      map: map
  });

  map.setCenter(location);
}
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>

运行代码