Show the direction between two points in Google Map Api indented

I want to use Google Map Api and direct the direction between two points. My map is partially covered by a gray rectangle in which some text may be displayed. The problem arises when the distance between two points is too far and one point is covered with a gray rectangle.

How can I make him draw a path so that the entire path is shown on the right side of the gray window, and none of the points overlap with a gray rectangle?

I currently have:

enter image description here

What I expect:

enter image description here

+3
google-maps google-maps-api-3
Sep 23 '14 at 10:15
source share
1 answer

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

+5
Oct 04 '14 at 11:39
source share



All Articles