Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - GMap Drawing tools to image jpeg [static map URL]

How to get the url of a gmap that was designed by entering circles, polygons and rectangles, as the image, using the Drawing tools? mapa desenhado need to get this custom map with the design and generate an image ... to find the url I create a Static Map and make the image, with the code below

                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);}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What needs to be done is to translate the various objects from the DrawingManager to paths (or markers) that can be rendered on a Static Map.

Below is a start at a DrawingManager to Static Map tool. It uses an approximation for circles (64 points), that can be adjusted. It is a proof of concept, not a complete application.

Note: the Static Maps has a maximum URL size, if too many objects are added it will fail. This code doesn't make any attempt to check the length.

proof of concept fiddle

code snippet:

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&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="imageholder"></div>
<div id="urllen"></div>
<div id="info

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...