Javascript 在谷歌地图上使用鼠标绘制多边形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2325670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw polygon using mouse on google maps
提问by Kunal
I need to draw polygon using mouse and mark a particular area on Google maps. The purpose is to mark an area on Google maps and then showing hotels and attractions on that area. The user will mark the hotels on Google map while creating them so the db will have their latitude and longitudes.
我需要使用鼠标绘制多边形并在 Google 地图上标记特定区域。目的是在谷歌地图上标记一个区域,然后在该区域显示酒店和景点。用户将在创建酒店时在 Google 地图上标记酒店,以便数据库拥有它们的纬度和经度。
How can I draw the polygon and fill it with a color as background to mark the area in Google Maps? I have read the API Manual “how to draw polygons?” basically you would need to mark multiple points and then combine them into a polygon. But I will need to do this using mouse drag, just like drawing a shape. Kindly help me out how to achieve this.
如何绘制多边形并用颜色填充它作为背景以在 Google 地图中标记该区域?我已经阅读了 API 手册“如何绘制多边形?” 基本上你需要标记多个点,然后将它们组合成一个多边形。但是我需要使用鼠标拖动来执行此操作,就像绘制形状一样。请帮助我如何实现这一目标。
采纳答案by Richard
you can use the Google MyMaps polygon editing tools in your appplication, maybe this will be ok for you?
您可以在您的应用程序中使用 Google MyMaps 多边形编辑工具,也许这适合您?
see http://googlemapsapi.blogspot.com/2008/05/love-my-maps-use-its-line-and-shape.html
见http://googlemapsapi.blogspot.com/2008/05/love-my-maps-use-its-line-and-shape.html
However if you want to implement this yourself it is basically this:
但是,如果你想自己实现它,它基本上是这样的:
add click listener to map.
添加点击监听器到地图。
repeat: store points that user clicks on in an array, and add a marker at this point. if it is the first marker add click listener to it
重复:将用户点击的点存储在一个数组中,并在此时添加一个标记。如果它是第一个标记,则向其添加单击侦听器
when user clicks on first marker, parse use the array of points to build your polygon
当用户点击第一个标记时,解析使用点数组来构建多边形
I don't have any code to show you, but I have implemented this myself in a previous company, so it can be done :)
我没有任何代码可以向您展示,但是我自己在以前的公司中实现了这一点,因此可以完成:)
回答by Drew Noakes
Here is some code (for the Google Maps JavaScript API version 3) that achieves what you want. It supports:
这是一些实现您想要的代码(适用于 Google Maps JavaScript API 版本 3)。它支持:
- clicking to append vertices.
- clicking on the first vertex again to close the path.
- dragging vertices.
- 单击以附加顶点。
- 再次单击第一个顶点以关闭路径。
- 拖动顶点。
It's undocumented, but hopefully you can see what it's doing easily enough.
它没有记录,但希望你可以很容易地看到它在做什么。
$(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);
});
});
回答by Michael Hellein
The Google Maps JavaScript API v3 provides a drawing library, http://code.google.com/apis/maps/documentation/javascript/overlays.html#drawing_tools
Google Maps JavaScript API v3 提供了一个绘图库,http://code.google.com/apis/maps/documentation/javascript/overlays.html#drawing_tools
You just need to enable the drawing tools (as shown the the example in the docs) and add event listeners for the creation of overlay types (as shown under the "Drawing Events" section).
您只需要启用绘图工具(如文档中的示例所示)并添加用于创建叠加类型的事件侦听器(如“绘图事件”部分所示)。
A quick example of its use would be: http://gmaps-samples-v3.googlecode.com/svn/trunk/drawing/drawing-tools.html
其使用的一个简单示例是:http: //gmaps-samples-v3.googlecode.com/svn/trunk/drawing/drawing-tools.html
回答by Daniel Vassallo
You may want to check out the Geometry Controlsof the GMaps Utility Library.
您可能要检查出的几何控制的的GMaps实用工具库。
For further reference, you may want to go through the GeometryControls Reference.
如需进一步参考,您可能需要阅读GeometryControls 参考。
回答by Okan SARICA
i made an example for myself. the code is below and also jsfiddle is avaible
我为自己做了一个例子。代码在下面,也可以使用 jsfiddle
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=drawing&callback=initMap" async defer></script>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon', 'circle']
},
polygonOptions: {
editable: true
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete',
function(event) {
event.overlay.set('editable', false);
drawingManager.setMap(null);
console.log(event.overlay);
});
}
</script>
https://jsfiddle.net/zgmdvsrz/
https://jsfiddle.net/zgmdvsrz/
you can set drawingcontrol to true if you want to show drawing manager
如果要显示绘图管理器,可以将drawingcontrol 设置为true
回答by Steve Midgley
The new Map Engines Lite is exactly the tool you're looking for I think: https://mapsengine.google.com/map/
我认为新的 Map Engines Lite 正是您正在寻找的工具:https: //mapsengine.google.com/map/
回答by Kishor N R
I have used following code to draw polygon on a map
我使用以下代码在地图上绘制多边形
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Drawing Tools</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
#map, html, body {
padding: 0;
margin: 0;
height: 100%;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript">
var geocoder;
var map;
var all_overlays = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
fillColor: '#FF1493'
};
var selectedShape;
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
markerOptions: {
draggable: true
},
polygonOptions: polyOptions
});
$('#enablePolygon').click(function() {
drawingManager.setMap(map);
drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
});
$('#resetPolygon').click(function() {
if (selectedShape) {
selectedShape.setMap(null);
}
drawingManager.setMap(null);
$('#showonPolygon').hide();
$('#resetPolygon').hide();
});
google.maps.event.addListener(drawingManager, 'polygoncomplete',
function(polygon) {
// var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath());
// $('#areaPolygon').html(area.toFixed(2)+' Sq meters');
$('#resetPolygon').show();
});
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
all_overlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) {
var coordinates = (polygon.getPath().getArray());
console.log(coordinates);
alert(coordinates);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</head>
<body>
<input type="button" id="enablePolygon" value="Calculate Area" />
<input type="button" id="resetPolygon" value="Reset" style="display: none;" />
<div id="showonPolygon" style="display:none;"><b>Area:</b> <span
id="areaPolygon"> </span></div>
<div id="map_canvas"></div>
</html>
回答by Dennis
There is a port of the API v2 drawing tools to API v3 @ http://nettique.free.fr/gmap/toolbar.html
API v2 绘图工具有一个端口到 API v3 @ http://nettique.free.fr/gmap/toolbar.html
回答by zipzit
There have been some significant improvements in google.maps.polygon since this question was first asked. Here's a simple implementation, using all native google.maps v3 tools. (Note: there is a wonky JavaScript scope work around here... but it does work...)
自从第一次提出这个问题以来,google.maps.polygon 已经有了一些重大改进。这是一个简单的实现,使用所有原生 google.maps v3 工具。(注意:这里有一个不稳定的 JavaScript 范围工作......但它确实有效......)
var listener1 = google.maps.event.addListener(map, "click", function(e) {
var latLng = e.latLng;
var myMvcArray = new google.maps.MVCArray();
myMvcArray.push(latLng); // First Point
var myPolygon = new google.maps.Polygon({
map: map,
paths: myMvcArray, // one time registration reqd only
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.10,
editable: true,
draggable: false,
clickable: true
});
google.maps.event.removeListener(listener1);
var listener2 = google.maps.event.addListener(map, 'click', function(e) {
latLng = e.latLng;
myMvcArray.push(latLng);
myMvcArray.getArray().forEach(function(value, index) {
console.log(" index: " + index + " value: " + value);
})
});
});
Answer with new code submitted on old question in case anybody else gets here!
用在旧问题上提交的新代码回答,以防其他人到达这里!


