通常情况下,Google Maps API 第 3 版中的用户界面事件会传递事件参数,您可通过事件侦听器访问这些参数,这些参数会注明事件发生时用户界面所处的状态。例如,用户界面 'click' 事件通常传递包含 latLng 属性的 MouseEvent,该属性指出了地图上的点击位置。请注意,这是用户界面事件所独有的行为;MVC 状态更改不会在它们的事件中传递参数。
您可以访问事件侦听器中的事件参数,这与访问对象属性的方法一样。以下示例介绍了如何为地图添加事件侦听器,以及如何在用户点击地图时,在所点击的位置处创建一个标记。
效果演示
代码
<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% } </style> <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"> </script> <script> var map; function initialize() { var myLatlng = new google.maps.LatLng(22.279566, 113.540955); var myOptions = { zoom: 12, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); google.maps.event.addListener(map, 'click', function(event) { placeMarker(event.latLng); }); } function placeMarker(location) { var marker = new google.maps.Marker({ position: location, map: map }); map.setCenter(location); } </script> </head> <body onload="initialize()"> <div id="map_canvas" style="width:100%; height:100%"></div> </body> </html>
延伸阅读
此文章所在专题列表如下:
- Google Maps API指南:在网页中嵌入GMaps
- Google Maps API指南:设置地图选项
- Google Maps API指南:地图标记与信息窗口
- Google Maps API指南:地图事件
- Google Maps API指南:点击添加标注
- Google Maps API指南:添加多个随机标注
本文地址:http://www.nowamagic.net/librarys/veda/detail/1691,欢迎访问原出处。
大家都在看