HTML画布作为相对于地图画布固定的Google地图中的Overlayview

时间:2011-05-11 07:09:30

标签: google-maps google-maps-api-3

我正在尝试将HTML5画布创建为地图大小的OverlayView,将其放置到top:0; left:0;,在其上绘制一些内容,然后将其添加到地图中。每当地图缩放或平移时,我想从地图中移除旧画布并在其上创建新的画布,将其定位到0,0并将其添加到地图中。但是地图永远不会重新定位到顶部:0;左:0。有人可以帮忙吗?

    function CustomLayer(map){
this.latlngs = new Array();
this.map_ = map;

this.addMarker = function(position){
this.latlngs.push(position);
}

this.drawCanvas = function(){
this.setMap(this.map_);
//google.maps.event.addListener(this.map_, 'bounds_changed',this.reDraw());
}

}

function defineOverlay() {

CustomLayer.prototype = new google.maps.OverlayView();

CustomLayer.prototype.onAdd = function() {
    console.log("onAdd()");
    if(this.canvas){    
    var panes = this.getPanes();
    panes.overlayLayer.appendChild(this.canvas);
    }
}


CustomLayer.prototype.remove = function() {
    console.log("onRemove()");
    if(this.canvas)
    this.canvas.parentNode.removeChild(this.canvas);
}


CustomLayer.prototype.draw = function() {
    console.log("draw()");
        this.remove();
            this.canvas = document.createElement("canvas");
            this.canvas.setAttribute('width', '800px');
            this.canvas.setAttribute('height', '480px');
            this.canvas.setAttribute('top', '30px');
            this.canvas.setAttribute('left', '30px');
            this.canvas.setAttribute('position', 'absolute');
            this.canvas.setAttribute('border', '1px solid red');
            this.canvas.style.border = '1px solid red';

            //using this way for some reason scale up the images and mess up the positions of the markers
            /*this.canvas.style.position = 'absolute';
            this.canvas.style.top = '0px';
            this.canvas.style.left = '0px';
            this.canvas.style.width = '800px'; 
            this.canvas.style.height = '480px';
            this.canvas.style.border = '1px solid red';*/

            //get the projection from this overlay
            overlayProjection = this.getProjection();
            //var mapproj = this.map_.getProjection();

                if(this.canvas.getContext) {
                    var context = this.canvas.getContext('2d');
                    context.clearRect(0,0,800,480);

                    for(i=0; i<this.latlngs.length; i++){

                        p = overlayProjection.fromLatLngToDivPixel(this.latlngs[i]);
                        //p = mapproj.fromLatLngToPoint(this.latlngs[i]);
                        img = new Image();
                        img.src = "standardtick.png";
                            console.log(Math.floor(p.x)+","+Math.floor(p.y));
                    context.drawImage(img,p.x,p.y);
                    }
                }
    this.onAdd();           
    console.log("canvas width:"+this.canvas.width+" canvas height: "+this.canvas.height);
    console.log("canvas top:"+this.canvas.getAttribute("top")+" left: "+this.canvas.getAttribute("left"));  
}
}

2 个答案:

答案 0 :(得分:5)

在这个例子中 - 我认为重要的是要关注projection.fromLatLngToDivPixel和projection.fromLatLngToContainerPixel之间的区别。在此上下文中,DivPixel用于将画布的位置保持在地图视图的中心位置 - 而ContainerPixel用于查找要绘制到画布的形状的位置。

以下是我自己解决这个问题的一个完整的工作示例。

叠加层所需的CSS属性:

  .GMAPS_OVERLAY
  {
    border-width: 0px;
    border: none;
    position:absolute;
    padding:0px 0px 0px 0px;
    margin:0px 0px 0px 0px;
  }

根据Google标记初始化地图并创建测试

  var mapsize    = { width: 500, height: 500 };
  var mapElement = document.getElementById("MAP");

  mapElement.style.height = mapsize.width + "px";
  mapElement.style.width  = mapsize.width + "px";

  var map = new google.maps.Map(document.getElementById("MAP"), {
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    center:    new google.maps.LatLng(0, 0),
    zoom:      2
  });

  // Render G-Markers to Test Proper Canvas-Grid Alignment
  for (var lng = -180; lng < 180; lng += 10)
  {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(0, lng),
      map: map
    });
  }

定义自定义叠加层

  var CanvasOverlay = function(map) {
    this.canvas           = document.createElement("CANVAS");
    this.canvas.className = "GMAPS_OVERLAY";
    this.canvas.height    = mapsize.height;
    this.canvas.width     = mapsize.width;
    this.ctx              = null;
    this.map              = map;

    this.setMap(map);
  };
  CanvasOverlay.prototype = new google.maps.OverlayView();

  CanvasOverlay.prototype.onAdd = function() {
    this.getPanes().overlayLayer.appendChild(this.canvas);
    this.ctx = this.canvas.getContext("2d");
    this.draw();
  };

  CanvasOverlay.prototype.drawLine = function(p1, p2) {
    this.ctx.beginPath();
    this.ctx.moveTo( p1.x, p1.y );
    this.ctx.lineTo( p2.x, p2.y );
    this.ctx.closePath();
    this.ctx.stroke();
  };

  CanvasOverlay.prototype.draw = function() {
    var projection = this.getProjection();

    // Shift the Canvas
    var centerPoint = projection.fromLatLngToDivPixel(this.map.getCenter());
    this.canvas.style.left = (centerPoint.x - mapsize.width  / 2) + "px";
    this.canvas.style.top  = (centerPoint.y - mapsize.height / 2) + "px";

    // Clear the Canvas
    this.ctx.clearRect(0, 0, mapsize.width, mapsize.height);

    // Draw Grid with Canvas
    this.ctx.strokeStyle = "#000000";
    for (var lng = -180; lng < 180; lng += 10)
    {
      this.drawLine(
        projection.fromLatLngToContainerPixel(new google.maps.LatLng(-90, lng)),
        projection.fromLatLngToContainerPixel(new google.maps.LatLng( 90, lng))
      );
    }
  };

初始化画布

我发现我想添加一个额外的电话来吸引“dragend”事件 - 但要测试它以了解您对您的需求的看法。

  var customMapCanvas = new CanvasOverlay(map);
  google.maps.event.addListener(map, "drawend", function() {
    customMapCanvas.draw();
  };

如果Canvas绘图正在减慢地图

在我使用的应用程序上,我发现Map Framework在画布上经常调用' draw '方法,这些方法正在绘制需要一秒左右才能完成的内容。在这种情况下,我将' draw '原型函数定义为一个空函数,同时将我的真实绘图函数命名为'canvasDraw' - 然后为“ zoomend “和” dragend “。你得到的是一个画布,只有在用户更改缩放级别或地图拖动操作结束后才会更新。

  CanvasOverlay.prototype.draw = function() { };      

  ... 

  google.maps.event.addListener(map, "dragend", function() {
    customMapCanvas.canvasDraw();
  });

  google.maps.event.addListener(map, "zoom_changed", function() {
    customMapCanvas.canvasDraw();
  });

现场演示:Complete Example - All Inline Source

答案 1 :(得分:0)

地图移动后,绘图上下文需要知道它已移动。

CustomOverlayView.prototype.alignDrawingPane = function(force) {
    window.mapProjection = this.getProjection(); 
    var center = window.mapProjection.fromLatLngToDivPixel(map.getCenter());
    //My drawing container is dragged along with the map when panning
    //this.drawPane refers to any node in MapPanes retrieved via this.getPanes()
    this.drawPane.css({left:center.x - (mapWidth/2), top:center.y-(mapHeight/2)});
};

在draw()方法中调用它。完成拖动后,确保调用绘图:

google.maps.event.addListener(map, 'dragend', function() {
    myCustomOverlay.draw();
});