我需要使用鼠标绘制多边形并在 Google map 上标记特定区域。目的是在谷歌地图上标记一个区域,然后显示该区域的酒店和景点。用户在创建酒店时会在谷歌地图上标记酒店,这样数据库就会有他们的经纬度。
如何绘制多边形并用颜色填充它作为背景以在 Google map 中标记该区域?我已经阅读了 API 手册“如何绘制多边形?”基本上你需要标记多个点,然后将它们组合成一个多边形。但我需要使用鼠标拖动来完成此操作,就像绘制形状一样。请帮助我了解如何实现这一目标。
最佳答案
这里有一些代码(针对 Google Maps JavaScript API 版本 3)可以实现您想要的功能。它支持:
- 点击附加顶点。
- 再次点击第一个顶点关闭路径。
- 拖动顶点。
它没有记录,但希望您能很容易地看到它在做什么。
$(document).ready(function () {
var map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(21.17, -86.66), zoom: 9, mapTypeId: google.maps.MapTypeId.HYBRID, scaleControl: true });
var isClosed = false;
var poly = new google.maps.Polyline({ map: map, path: [], strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2 });
google.maps.event.addListener(map, 'click', function (clickEvent) {
if (isClosed)
return;
var markerIndex = poly.getPath().length;
var isFirstMarker = markerIndex === 0;
var marker = new google.maps.Marker({ map: map, position: clickEvent.latLng, draggable: true });
if (isFirstMarker) {
google.maps.event.addListener(marker, 'click', function () {
if (isClosed)
return;
var path = poly.getPath();
poly.setMap(null);
poly = new google.maps.Polygon({ map: map, path: path, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35 });
isClosed = true;
});
}
google.maps.event.addListener(marker, 'drag', function (dragEvent) {
poly.getPath().setAt(markerIndex, dragEvent.latLng);
});
poly.getPath().push(clickEvent.latLng);
});
});
关于javascript - 在谷歌地图上使用鼠标绘制多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2325670/