很多地图定位等需要有电子围栏功能,正巧最近在做某个定位项目也需要这个功能。google了一下没发现好用的代码只好写自己一个了。
很简单,直接上代码
<! DOCTYPE html > < html > < head > < meta name ="viewport" content ="initial-scale=1.0, user-scalable=no" /> < meta http-equiv ="content-type" content ="text/html; charset=UTF-8" /> < title > Google Maps JavaScript API v3 Example: Marker Simple </ title > < link href ="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel ="stylesheet" type ="text/css" /> < script type ="text/javascript" src ="http://maps.googleapis.com/maps/api/js?sensor=false" ></ script > < script type ="text/javascript" > function initialize() { var myLatlng = new google.maps.LatLng( 29.678815 , 121.426489 ); var myOptions = { zoom: 12 , center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById( " map_canvas " ), myOptions); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: " Hello World! " }); var rectangle = new google.maps.Rectangle(); var rectOptions = { strokeColor: " #FF0000 " , strokeOpacity: 0.8 , strokeWeight: 2 , fillColor: " #FF0000 " , fillOpacity: 0.35 , map: map, clickable: false , bounds: map.getBounds() }; var beginlatlng = "" ; // 记录起始点坐标 var endlatlng = "" ; // 记录结束点坐标 var rectBounds = "" ; var SfClick = "" ; var SfMove = "" ; var ClickCount = 0 ; // 点击次数 SfClick = google.maps.event.addListener(map, ' click ' , function (e) { var begin = e.latLng; ClickCount ++ ; if (ClickCount == 1 ) { SfMove = google.maps.event.addListener(map, " mousemove " , function (e) { beginlatlng = begin; endlatlng = e.latLng; rectOptions.bounds = new google.maps.LatLngBounds(beginlatlng, endlatlng); rectOptions.map = map; rectangle.setOptions(rectOptions); }); } else { google.maps.event.removeListener(SfMove); if (window.confirm( " 确定该电子围栏范围吗? " )) { ClickCount = 0 ; alert( ' 起始坐标点 ' + beginlatlng + ' \n结束坐标点 ' + endlatlng) } else { ClickCount = 0 ; rectOptions.map = null ; rectangle.setOptions(rectOptions); } } });} </ script > </ head > < body onLoad ="initialize()" > < div id ="map_canvas" ></ div > </ body >
</html>
注意 Rectangle 的clickable一定要设置为falsh,否则矩形结束不了。如果您在转载的时候能带上出处最好