Search code examples
javascriptjquerygoogle-mapsgoogle-polyline

Google map path doesn't cross International Dateline using epoly.js


I'm making a marker move from point A to point B by using the .GetPointDistance from epoly.js in a loop. It works fine as long as the shortest distance does not cross the Intl Dateline. If it does, like going from San Francisco, to Tokyo, it travels eastbound the long way around instead of crossing the pacific (Google polyline will draw it correctly) Here's my code

function myLoop () {
          setTimeout(function () {

            var point = flightPath.GetPointAtDistance(newDistance);
            marker.setPosition(point);

            if (newDistance < legDistance) {
              myLoop();
            } else {

              if (testArray.length > 0) {
                flightPathShadow.setMap(map);
                flightPath.setMap(map);

                x = testArray.shift();
                newDistance = 0;
                loopWrapper();
              }
            }

            oldDistance = newDistance;
            newDistance = newDistance + travelDistance;
            totalDistance = (totalDistance + travelDistance);
            var milesDistance = totalDistance*0.000621371;
            milesDistance = Math.round(milesDistance);
            milesDistance = addCommas(milesDistance);
            $("#dashboard").html("<h4>" + milesDistance + " miles traveled</h4>");

          }, travelTime)
        }

Here's the function in epoly.js

google.maps.Polygon.prototype.GetPointAtDistance = function(metres) {
  if (metres == 0) return this.getPath().getAt(0);
  if (metres < 0) return null;
  if (this.getPath().getLength() < 2) return null;
  var dist=0;
  var olddist=0;
  for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
    olddist = dist;
    dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
  }
  if (dist < metres) {
    return null;
  }
  var p1= this.getPath().getAt(i-2);
  var p2= this.getPath().getAt(i-1);
  var m = (metres-olddist)/(dist-olddist);
  return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
}

Solution

  • If you add a point on the International Date Line, it works

    example

    Includes these points:

    <point lat="37.77493" lng="-122.419416"/>
    <point lat="39.614028" lng="-179.906751"/>
    <point lat="39.904211" lng="116.407395"/>