I was not satisfied with the answers here. So I did some experiments and found the โsimplestโ working solution that is close to Ralphโs answer, but hopefully more understandable. (I want Google to make this feature more accessible!)
First, you declare a subclass of OverlayView somewhere like this:
function CanvasProjectionOverlay() {} CanvasProjectionOverlay.prototype = new google.maps.OverlayView(); CanvasProjectionOverlay.prototype.constructor = CanvasProjectionOverlay; CanvasProjectionOverlay.prototype.onAdd = function(){}; CanvasProjectionOverlay.prototype.draw = function(){}; CanvasProjectionOverlay.prototype.onRemove = function(){};
Then, somewhere else in your code where you create the map instance, you also create an instance of this OverlayView and set its map, for example:
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);
Then, when you need to use fromLatLngToContainerPixel , you simply do this:
canvasProjectionOverlay.getProjection().fromLatLngToContainerPixel(myLatLng);
Please note that since the MapCanvasProjection object will only be available after calling draw() , which once was before the idle map, I suggest creating a logical flag "mapInitialized", setting it to true on the first idle map callback. And then do what you need to do only after that.
pixelfreak Aug 10 2018-11-11T00: 00Z
source share