将谷歌地图折线转换为html画布线

时间:2015-11-21 09:55:55

标签: javascript google-maps html5-canvas

我需要将Google地图折线显示为html画布。我如何转换这样的坐标:

lat:25.5643498,lng:45.34492432 

像这样的画布坐标?

x:230,y:445

我试图"规模"从谷歌坐标向下但没有成功。

1 个答案:

答案 0 :(得分:1)

使用MapCanvasProjection方法.fromLatLngToContainerPixel

proof of concept fiddle

代码段

var geocoder;
var map;
var overlay;
var shapes = [];


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
    });
  overlay = new google.maps.OverlayView();
  overlay.draw = function() {};
  overlay.setMap(map);
  var 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.POLYLINE
      ]
    }
  });
  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    if (event.type == google.maps.drawing.OverlayType.POLYLINE) {
      if (drawingManager.getDrawingMode()) {
        drawingManager.setDrawingMode(null);
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      context.clearRect(0, 0, canvas.width, canvas.height);
      var polyline = event.overlay;
      shapes.push(polyline);
      context.beginPath();
      for (var i = 0; i < polyline.getPath().getLength(); i++) {
        var point = overlay.getProjection().fromLatLngToContainerPixel(polyline.getPath().getAt(i));
        if (i == 0) {
          context.moveTo(point.x, point.y);
        } else {
          context.lineTo(point.x, point.y);
        }
      }
      context.stroke();
    }
  });
  drawingManager.setMap(map);
  google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
    if (drawingManager.getDrawingMode() != null) {
      for (var i = 0; i < shapes.length; i++) {
        shapes[i].setMap(null);
      }
      shapes = [];
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
{
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
#map_canvas {
  height: 400px;
  width: 500px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
<canvas id="myCanvas" width="500" height="400"></canvas>
<div id="map_canvas"></div>