GMap绘图工具图像jpeg [静态地图URL]

时间:2015-07-07 19:03:57

标签: javascript html google-maps google-maps-api-3 jpeg

如何使用绘图工具获取通过输入圆,多边形和矩形作为图像设计的gmap的网址? mapa desenhado 需要使用设计获取此自定义地图并生成图像... 找到网址我创建一个静态地图并使用下面的代码制作图像

                this.showImage = function () {
                var url = "http://maps.googleapis.com/maps/api/staticmap?center=" + map.center + "&zoom=" + map.zoom + "&size=800x600&sensor=false"
                var div = document.getElementById('mapImg');
                var img = document.createElement('img');
               img.src = url;
                div.appendChild(img);}

1 个答案:

答案 0 :(得分:3)

需要做的是将各种对象从DrawingManager转换为可以在Static Map上呈现的路径(或标记)。

下面是DrawingManager到静态地图工具的开始。它使用圆的近似值(64点),可以调整。这是一个概念证明,而不是一个完整的应用程序。

注意:静态地图具有最大网址大小,如果添加的对象太多,则会失败。此代码不会尝试检查长度。

proof of concept fiddle

代码段

function createStaticMap() {
  var fillC, strokeC, weight, path;
  var staticMap = "https://maps.googleapis.com/maps/api/staticmap?size=512x512&maptype=roadmap";
  for (var i = 0; i < overlays.length; i++) {
    if (overlays[i].type == google.maps.drawing.OverlayType.POLYGON || overlays[i].type == google.maps.drawing.OverlayType.POLYLINE) {
      path = encodeURIComponent(google.maps.geometry.encoding.encodePath(overlays[i].overlay.getPath()));
      if (overlays[i].type == google.maps.drawing.OverlayType.POLYGON) {
        fillC = overlays[i].overlay.get("fillColor");
        strokeC = overlays[i].overlay.get("strokeColor");
        weight = overlays[i].overlay.get("strokeWeight");
        staticMap += "&path=";
        if (typeof fillC != "undefined") staticMap += "fillcolor:" + fillC.replace(/#/, "0x");
        if (typeof weight != "undefined") staticMap += "%7Cweight:" + weight;
        else staticMap += "%7Cweight:0";
        if (typeof strokeC != "undefined") staticMap += "%7Ccolor:" + strokeC.replace(/#/, "0x");
        staticMap += "%7Cenc:" + path;
      } else if (overlays[i].type == google.maps.drawing.OverlayType.POLYLINE) {
        fillC = overlays[i].overlay.get("fillColor");
        strokeC = overlays[i].overlay.get("strokeColor");
        weight = overlays[i].overlay.get("strokeWeight");

        staticMap += "&path=";
        if (typeof weight != "undefined") staticMap += "weight:" + weight;
        else staticMap += "weight:2";
        if (typeof strokeC != "undefined") staticMap += "%7Ccolor:" + strokeC.replace(/#/, "0x");
        staticMap += "%7Cenc:" + path;
      }
    } else if (overlays[i].type == google.maps.drawing.OverlayType.MARKER) {
      staticMap += "&markers=color:blue|" + overlays[i].overlay.getPosition().toUrlValue(6);

    } else if (overlays[i].type == google.maps.drawing.OverlayType.RECTANGLE) {
      path = [];
      var north = overlays[i].overlay.getBounds().getNorthEast().lat();
      var east = overlays[i].overlay.getBounds().getNorthEast().lng();
      var south = overlays[i].overlay.getBounds().getSouthWest().lat();
      var west = overlays[i].overlay.getBounds().getSouthWest().lng();
      path.push(new google.maps.LatLng(north, east));
      path.push(new google.maps.LatLng(south, east));
      path.push(new google.maps.LatLng(south, west));
      path.push(new google.maps.LatLng(north, west));
      path.push(new google.maps.LatLng(north, east));
      path = encodeURIComponent(google.maps.geometry.encoding.encodePath(path));
      fillC = overlays[i].overlay.get("fillColor");
      strokeC = overlays[i].overlay.get("strokeColor");
      weight = overlays[i].overlay.get("strokeWeight");
      staticMap += "&path=";
      if (typeof fillC != "undefined") staticMap += "fillcolor:" + fillC.replace(/#/, "0x");
      else staticMap += "fillcolor:blue";
      if (typeof weight != "undefined") staticMap += "%7Cweight:" + weight;
      if (typeof strokeC != "undefined") staticMap += "%7Ccolor:" + strokeC.replace(/#/, "0x");
      staticMap += "%7Cenc:" + path;
    } else if (overlays[i].type == google.maps.drawing.OverlayType.CIRCLE) {
      path = drawCircle(overlays[i].overlay.getCenter(),
        overlays[i].overlay.getRadius(), 1);
      path = encodeURIComponent(google.maps.geometry.encoding.encodePath(path));
      fillC = overlays[i].overlay.get("fillColor");
      strokeC = overlays[i].overlay.get("strokeColor");
      weight = overlays[i].overlay.get("strokeWeight");
      staticMap += "&path=";
      if (typeof fillC != "undefined") staticMap += "fillcolor:" + fillC.replace(/#/, "0x");
      else staticMap += "fillcolor:blue";
      if (typeof weight != "undefined") staticMap += "%7Cweight:" + weight;
      if (typeof strokeC != "undefined") staticMap += "%7Ccolor:" + strokeC.replace(/#/, "0x");
      staticMap += "%7Cenc:" + path;
    }
  }
  document.getElementById('staticMap').innerHTML = staticMap;
  document.getElementById('imageholder').innerHTML = "<img src='" + staticMap + "' alt='static map' / > ";
document.getElementById('urllen').innerHTML = "URL length =" + staticMap.length + " characters";
}


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

function initialize() {
  geocoder = new google.maps.Geocoder();
  var mapOptions = {
    center: new google.maps.LatLng(-27.37777, -51.592762),
    zoom: 16
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
  google.maps.event.addListener(map, 'click', function(evt) {
    document.getElementById('info').innerHTML = evt.latLng.toUrlValue(6);
  });

  var polyOptions = {
    strokeWeight: 0,
    fillOpacity: 0.45,
    editable: true
  };

  drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [
        google.maps.drawing.OverlayType.MARKER,
        google.maps.drawing.OverlayType.CIRCLE,
        google.maps.drawing.OverlayType.POLYGON,
        google.maps.drawing.OverlayType.POLYLINE,
        google.maps.drawing.OverlayType.RECTANGLE
      ]
    },
    markerOptions: {
      icon: 'http://maps.google.com/mapfiles/ms/micons/blue.png',
      draggable: true
    },
    polylineOptions: {
      editable: true
    },
    rectangleOptions: polyOptions,
    circleOptions: polyOptions,
    polygonOptions: polyOptions
  });
  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(ovrly) {
    if (ovrly.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 = ovrly.overlay;
      newShape.type = ovrly.type;
      google.maps.event.addListener(newShape, 'click', function() {
        setSelection(newShape);
      });
      setSelection(newShape);
    }

    overlays.push(ovrly);
  });
  drawingManager.setMap(map);

  // 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);

function drawCircle(point, radius, dir) {
  var d2r = Math.PI / 180; // degrees to radians 
  var r2d = 180 / Math.PI; // radians to degrees 
  var earthsradius = 6371.0 * 1000.0; // meters; 6371.0 is the radius of the earth in km
  var points = 64;
  var start, end;

  // find the raidus in lat/lon 
  var rlat = (radius / earthsradius) * r2d;
  var rlng = rlat / Math.cos(point.lat() * d2r);
  var extp = [];
  if (dir == 1) {
    start = 0;
    end = points + 1;
  } // one extra here makes sure we connect the
  else {
    start = points + 1;
    end = 0;
  }
  for (var i = start;
    (dir == 1 ? i < end : i > end); i = i + dir) {
    var theta = Math.PI * (i / (points / 2));
    ey = point.lng() + (rlng * Math.cos(theta)); // center a + radius x * cos(theta) 
    ex = point.lat() + (rlat * Math.sin(theta)); // center b + radius y * sin(theta) 
    extp.push(new google.maps.LatLng(ex, ey));
  }
  // alert(extp.length);
  return extp;
}


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]);
}
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
#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;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
<div id="imageholder"></div>
<div id="urllen"></div>
<div id="info"></div>
<div id="panel">
  <div id="color-palette"></div>
  <div>
    <button id="delete-button">Delete Selected Shape</button>
  </div>
</div>
<input type="button" value="create Static Map" onclick="createStaticMap()" />
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>
<div id="staticMap"></div>