Google Maps Draw Tool输出多边形坐标 [英] Google Maps Draw Tool outputting polygon coordinates

查看:63
本文介绍了Google Maps Draw Tool输出多边形坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了这个答案,但到目前为止我还无法给出明确的答案...

I have searched SO for this answer and I haven't been able to come up with a definitive answer as of yet...

这是问题所在:当我尝试将多边形坐标写入console时,如果选择的工具是多边形,它将起作用.但是,当我使用正方形或圆形时,会出现错误

Here's the problem: When I try to write my polygon coordinates to console it works if the tool chosen is a polygon. However when I use Square or Circle, I get the error

e.overlay.getPath is not a function

使用我当前的代码,我认为else应该抓住正方形和圆形.显然我误会了...

With my current code, I am thinking that the else should catch the square and circle. Obviously I am mistaken ...

这就是我所拥有的:

if (e.type == google.maps.drawing.OverlayType.POLYLINE || google.maps.drawing.OverlayType.POLYGON) {
            var locations = e.overlay.getPath().getArray()
            //console.log(bounds.toString());    
            console.log(locations.toString() + " 1st instace");
        }
        else {
            //get lat/lng bounds of the current shape
            var bounds = e.overlay.getBounds();
            var start = bounds.getNorthEast();
            var end = bounds.getSouthWest();
            var center = bounds.getCenter();
            //console.log(bounds.toString());    
            consol.log(bounds.toString() + " 2nd instance");
        }

整个片段:

var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};

function clearSelection() {
  if (selectedShape) {
    selectedShape.setEditable(false);
    selectedShape = null;
  }
}

function setSelection(shape) {
  clearSelection();
  selectedShape = shape;
  shape.setEditable(true);
  selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}

function deleteSelectedShape() {
  if (selectedShape) {
    selectedShape.setMap(null);
  }
}

function selectColor(color) {
  selectedColor = color;
  for (var i = 0; i < colors.length; ++i) {
    var currColor = colors[i];
    colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
  }

  // Retrieves the current options from the drawing manager and replaces the
  // stroke or fill color as appropriate.
  var polylineOptions = drawingManager.get('polylineOptions');
  polylineOptions.strokeColor = color;
  drawingManager.set('polylineOptions', polylineOptions);

  var rectangleOptions = drawingManager.get('rectangleOptions');
  rectangleOptions.fillColor = color;
  drawingManager.set('rectangleOptions', rectangleOptions);

  var circleOptions = drawingManager.get('circleOptions');
  circleOptions.fillColor = color;
  drawingManager.set('circleOptions', circleOptions);

  var polygonOptions = drawingManager.get('polygonOptions');
  polygonOptions.fillColor = color;
  drawingManager.set('polygonOptions', polygonOptions);
}

function setSelectedShapeColor(color) {
  if (selectedShape) {
    if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
      selectedShape.set('strokeColor', color);
    } else {
      selectedShape.set('fillColor', color);
    }
  }
}

function makeColorButton(color) {
  var button = document.createElement('span');
  button.className = 'color-button';
  button.style.backgroundColor = color;
  google.maps.event.addDomListener(button, 'click', function() {
    selectColor(color);
    setSelectedShapeColor(color);
  });

  return button;
}

function buildColorPalette() {
  var colorPalette = document.getElementById('color-palette');
  for (var i = 0; i < colors.length; ++i) {
    var currColor = colors[i];
    var colorButton = makeColorButton(currColor);
    colorPalette.appendChild(colorButton);
    colorButtons[currColor] = colorButton;
  }
  selectColor(colors[0]);
}

function showArrays(event) {
  // Since this polygon has only one path, we can call getPath() to return the
  // MVCArray of LatLngs.
  var vertices = this.getPath();

  var contentString = '<b>Bermuda Triangle polygon</b><br>' +
    'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
    '<br>';

  // Iterate over the vertices.
  for (var i = 0; i < vertices.getLength(); i++) {
    var xy = vertices.getAt(i);
    contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
      xy.lng();
  }
}


function initialize() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(acheived_lat, acheived_lon),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true,
    zoomControl: true
  });
  var polyOptions = {
    strokeWeight: 0,
    fillOpacity: 0.45,
    editable: true
  };
  // Creates a drawing manager attached to the map that allows the user to draw
  // markers, lines, and shapes.
  drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    markerOptions: {
      draggable: true
    },
    polylineOptions: {
      editable: true
    },
    rectangleOptions: polyOptions,
    circleOptions: polyOptions,
    polygonOptions: polyOptions,
    map: map
  });

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(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);

      if (e.type == google.maps.drawing.OverlayType.POLYLINE || google.maps.drawing.OverlayType.POLYGON) {
        var locations = e.overlay.getPath().getArray()
          //console.log(bounds.toString());    
        alert(locations.toString() + " 1st instace");
      } else {
        //get lat/lng bounds of the current shape
        var bounds = e.overlay.getBounds();
        var start = bounds.getNorthEast();
        var end = bounds.getSouthWest();
        var center = bounds.getCenter();
        //console.log(bounds.toString());    
        alert(bounds.toString() + " 2nd instance");
      }
    }
  });

  // Clear the current selection when the drawing mode is changed, or when the
  // map is clicked.
  google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
  google.maps.event.addListener(map, 'click', clearSelection);
  google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);

  buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);

#map div {
  width: auto;
}
#map {
  height: 500px;
  width: 80%;
  margin-top: 32px;
}
#map,
html,
body {
  padding: 0;
  margin: 0;
  width: 960px;
  height: 300px;
}
#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;
}

<div id="map"></div>

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false&libraries=drawing">
</script>
<script>
  window.acheived_lat = 36.825230;
  window.acheived_lon = -119.702919;
</script>
<div id="panel">
  <div id="color-palette"></div>
  <div>
    <button id="delete-button">Delete Selected Shape</button>
  </div>
</div>

我知道这可能与其他问题有关.我已经在主if中尝试过|| SQUARE,但无济于事.难过!

I know it's probably something that has to do with the else. I have tried || SQUARE in the main if as well to no avail. Stumped!

推荐答案

google .maps.Circle 对象和 google.maps.Rectangle 对象没有getPath方法.您可以计算等效路径以制作等效的多边形,或保存它们替代使用的数据.

google.maps.Circle objects and google.maps.Rectangle objects don't have a getPath methods. You can compute the equivalent path to make an equivalent Polygon, or save the data they use instead.

  • Circle is defined by its center and radius (a google.maps.LatLng object and a distance in meters)
  • Rectangle is defined by its bounds (a google.maps.LatLngBounds object)

此外,此行没有达到您的期望:

Also, this line isn't doing what you expect:

if (e.type == google.maps.drawing.OverlayType.POLYLINE || google.maps.drawing.OverlayType.POLYGON) {

应该是:

  if ((e.type == google.maps.drawing.OverlayType.POLYLINE) || (e.type == google.maps.drawing.OverlayType.POLYGON)) {

代码段:

var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};

function initialize() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(acheived_lat, acheived_lon),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true,
    zoomControl: true
  });
  var polyOptions = {
    strokeWeight: 0,
    fillOpacity: 0.45,
    editable: true
  };
  // Creates a drawing manager attached to the map that allows the user to draw
  // markers, lines, and shapes.
  drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    markerOptions: {
      draggable: true
    },
    polylineOptions: {
      editable: true
    },
    rectangleOptions: polyOptions,
    circleOptions: polyOptions,
    polygonOptions: polyOptions,
    map: map
  });

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(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);

      if ((e.type == google.maps.drawing.OverlayType.POLYLINE) || (e.type == google.maps.drawing.OverlayType.POLYGON)) {
        var locations = e.overlay.getPath().getArray()
        console.log("POLY:" + locations.toString());
        //alert(locations.toString() + " 1st instace");
      } else if (e.type == google.maps.drawing.OverlayType.CIRCLE) {
        console.log("CIRCLE center=" + e.overlay.getCenter().toUrlValue(6) + " radius=" + e.overlay.getRadius());

      } else if (e.type == google.maps.drawing.OverlayType.RECTANGLE) {
        //get lat/lng bounds of the current shape
        var bounds = e.overlay.getBounds();
        var start = bounds.getNorthEast();
        var end = bounds.getSouthWest();
        var center = bounds.getCenter();
        console.log("RECTANGLE:" + bounds.toString());
        // alert(bounds.toString() + " 2nd instance");
      }
    }
  });

  // Clear the current selection when the drawing mode is changed, or when the
  // map is clicked.
  google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
  google.maps.event.addListener(map, 'click', clearSelection);
  google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);

  buildColorPalette();
}

function clearSelection() {
  if (selectedShape) {
    selectedShape.setEditable(false);
    selectedShape = null;
  }
}

function setSelection(shape) {
  clearSelection();
  selectedShape = shape;
  shape.setEditable(true);
  selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}

function deleteSelectedShape() {
  if (selectedShape) {
    selectedShape.setMap(null);
  }
}

function selectColor(color) {
  selectedColor = color;
  for (var i = 0; i < colors.length; ++i) {
    var currColor = colors[i];
    colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
  }

  // Retrieves the current options from the drawing manager and replaces the
  // stroke or fill color as appropriate.
  var polylineOptions = drawingManager.get('polylineOptions');
  polylineOptions.strokeColor = color;
  drawingManager.set('polylineOptions', polylineOptions);

  var rectangleOptions = drawingManager.get('rectangleOptions');
  rectangleOptions.fillColor = color;
  drawingManager.set('rectangleOptions', rectangleOptions);

  var circleOptions = drawingManager.get('circleOptions');
  circleOptions.fillColor = color;
  drawingManager.set('circleOptions', circleOptions);

  var polygonOptions = drawingManager.get('polygonOptions');
  polygonOptions.fillColor = color;
  drawingManager.set('polygonOptions', polygonOptions);
}

function setSelectedShapeColor(color) {
  if (selectedShape) {
    if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
      selectedShape.set('strokeColor', color);
    } else {
      selectedShape.set('fillColor', color);
    }
  }
}

function makeColorButton(color) {
  var button = document.createElement('span');
  button.className = 'color-button';
  button.style.backgroundColor = color;
  google.maps.event.addDomListener(button, 'click', function() {
    selectColor(color);
    setSelectedShapeColor(color);
  });

  return button;
}

function buildColorPalette() {
  var colorPalette = document.getElementById('color-palette');
  for (var i = 0; i < colors.length; ++i) {
    var currColor = colors[i];
    var colorButton = makeColorButton(currColor);
    colorPalette.appendChild(colorButton);
    colorButtons[currColor] = colorButton;
  }
  selectColor(colors[0]);
}

function showArrays(event) {
  // Since this polygon has only one path, we can call getPath() to return the
  // MVCArray of LatLngs.
  var vertices = this.getPath();

  var contentString = '<b>Bermuda Triangle polygon</b><br>' +
    'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
    '<br>';

  // Iterate over the vertices.
  for (var i = 0; i < vertices.getLength(); i++) {
    var xy = vertices.getAt(i);
    contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
      xy.lng();
  }
}
google.maps.event.addDomListener(window, 'load', initialize);

#map div {
  width: auto;
}
#map {
  height: 500px;
  width: 80%;
  margin-top: 32px;
}
#map,
html,
body {
  padding: 0;
  margin: 0;
  width: 960px;
  height: 300px;
}
#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;
}

<div id="map"></div>

<script type="text/javascript" src="https://maps.google.com/maps/api/js?libraries=drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>
<script>
  window.acheived_lat = 36.825230;
  window.acheived_lon = -119.702919;
</script>
<div id="panel">
  <div id="color-palette"></div>
  <div>
    <button id="delete-button">Delete Selected Shape</button>
  </div>
</div>

这篇关于Google Maps Draw Tool输出多边形坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆