在谷歌地图上使用鼠标绘制多边形

时间:2010-02-24 11:49:49

标签: javascript google-maps

我需要使用鼠标绘制多边形并在Google地图上标记特定区域。目的是在Google地图上标记一个区域,然后显示该区域的酒店和景点。用户将在创建它们时在Google地图上标记酒店,以便数据库具有纬度和经度。

如何绘制多边形并用颜色填充背景以在Google地图中标记区域?我已经阅读了API手册“如何绘制多边形?”基本上你需要标记多个点,然后将它们组合成一个多边形。但我需要使用鼠标拖动来完成此操作,就像绘制一个形状一样。请帮助我实现这一目标。

9 个答案:

答案 0 :(得分:27)

以下是一些可以实现您想要的代码(适用于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);
    });
});

答案 1 :(得分:20)

Google Maps JavaScript API v3提供了一个绘图库http://code.google.com/apis/maps/documentation/javascript/overlays.html#drawing_tools

您只需启用绘图工具(如文档中的示例所示)并添加事件侦听器以创建叠加类型(如“绘图事件”部分所示)。

使用它的一个简单示例是:http://gmaps-samples-v3.googlecode.com/svn/trunk/drawing/drawing-tools.html

答案 2 :(得分:16)

您可以在appplication中使用Google MyMaps多边形编辑工具,也许这对您有用吗?

请参阅http://googlemapsapi.blogspot.com/2008/05/love-my-maps-use-its-line-and-shape.html

但是如果你想自己实现它,基本上就是这样:

添加点击监听器以进行映射。

重复:  存储用户在数组中单击的点,并在此处添加标记。  如果它是第一个标记添加点击监听器

当用户点击第一个标记时,解析使用点数组来构建多边形

我没有任何代码可以向您展示,但我已经在以前的公司中实现了这一点,所以可以这样做:)

答案 3 :(得分:9)

您可能需要查看Geometry ControlsGMaps Utility Library

如需进一步参考,您可能需要浏览GeometryControls Reference

答案 4 :(得分:3)

我认为新的Map Engines Lite正是您正在寻找的工具:https://mapsengine.google.com/map/

答案 5 :(得分:2)

我为自己做了一个例子。代码在下面,也可以使用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/

如果要显示绘图管理器

,可以将drawingcontrol设置为true

答案 6 :(得分:1)

API v3 @ http://nettique.free.fr/gmap/toolbar.html

有一个API v2绘图工具的端口

答案 7 :(得分:1)

我使用以下代码在地图上绘制多边形

<!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">&nbsp;</span></div>
     <div id="map_canvas"></div>
     </html>

输出:enter image description here

答案 8 :(得分:0)

自问这个问题以来,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);
        })
    });
});

回答旧问题上提交的新代码,以防有人来到这里!