Since I have already seen several questions about SO about the displacement of material that would appear behind the elements superimposed on the map, I thought I would give it a little time.
Here is how I did it:
Highlight the route on the map and listen to the idle map event before starting with an offset.
Check the leftmost point of the route boundary to see if it lags behind the overlay. This uses the fromLatLngToPoint() method to translate from lat / lng coordinates to a point on the map projection.
Check how much you can compensate for the route by comparing the left and rightmost points of the route with the available space on the map. Slide the map until both points fit on the map canvas.
If both points cannot fit into the map canvas, zoom out and start the same process again.
The script should know the width of the overlay, and you should apply some fields so that it always fits nicely.
Here is the function used to translate between coordinates and point:
function fromLatLngToPoint(latLng) { var scale = Math.pow(2, map.getZoom()); var nw = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getSouthWest().lng()); var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw); var worldCoordinate = map.getProjection().fromLatLngToPoint(latLng); return new google.maps.Point(Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale), Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)); }
Here is a demo:
Jsfiddle demo
I'm sure it can still be optimized, but it does an excellent job of this. Please report problems here if you find.
Edit:
The same technique works with markers:
Jsfiddle demo
MrUpsidown Oct 04 '14 at 11:39 2014-10-04 11:39
source share