谷歌地图 - 活动
Google Maps JavaScript 程序可以响应用户生成的各种事件。本章提供了演示如何在使用 Google 地图时执行事件处理的示例。
添加事件监听器
您可以使用addListener()方法添加事件侦听器。它接受参数,例如我们要添加侦听器的对象名称、事件名称和处理程序事件。
例子
以下示例演示如何向标记对象添加事件侦听器。每次我们双击标记时,程序都会将地图的缩放值提高 5。
<!DOCTYPE html> <html> <head> <script src = "https://maps.googleapis.com/maps/api/js"></script> <script> var myCenter = new google.maps.LatLng(17.433053, 78.412172); function loadMap(){ var mapProp = { center: myCenter, zoom:5, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new google.maps.Marker({ position: myCenter, title:'Click to zoom' }); marker.setMap(map); //Zoom to 7 when clicked on marker google.maps.event.addListener(marker,'click',function() { map.setZoom(9); map.setCenter(marker.getPosition()); }); } </script> </head> <body onload = "loadMap()"> <div id = "googleMap" style = "width:580px; height:400px;"></div> </body> </html>
它产生以下输出 -
单击时打开信息窗口
以下代码在单击标记时打开一个信息窗口 -
<!DOCTYPE html> <html> <head> <script src = "https://maps.googleapis.com/maps/api/js"></script> <script> var myCenter = new google.maps.LatLng(17.433053, 78.412172); function loadMap(){ var mapProp = { center:myCenter, zoom:4, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new google.maps.Marker({ position:myCenter, }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"Hi" }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } </script> </head> <body onload = "loadMap()"> <div id = "googleMap" style = "width:580px; height:400px;"></div> </body> </html>
它产生以下输出 -
删除监听器
您可以使用方法removeListener()删除现有侦听器。该方法接受侦听器对象,因此我们必须将侦听器分配给一个变量并将其传递给该方法。
例子
以下代码显示了如何删除侦听器 -
<!DOCTYPE html> <html> <head> <script src = "https://maps.googleapis.com/maps/api/js"></script> <script> var myCenter = new google.maps.LatLng(17.433053, 78.412172); function loadMap(){ var mapProp = { center:myCenter, zoom:4, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new google.maps.Marker({ position:myCenter, }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"Hi" }); var myListener = google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); google.maps.event.removeListener(myListener); } </script> </head> <body onload = "loadMap()"> <div id = "googleMap" style = "width:580px; height:400px;"></div> </body> </html>
它产生以下输出 -