HTML 画布作为 Google 地图中的叠加视图,相对于地图画布是固定的



我正在尝试创建一个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"));  
}
}

在这个例子中 - 我认为重要的是要提请注意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();
  };

在画布绘制减慢地图速度

的情况下

在我使用的应用程序上,我发现地图框架在画布上经常调用"draw"方法,这些画布绘制的内容需要一秒钟左右才能完成。 在这种情况下,我将"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();
  });

现场演示:完整示例 - 所有内联源

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

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();
});

最新更新