1

I am trying to get middle point of a line (a line in a rectangle polygon), but following code does not give me correct answer. The number is too small. Can anyone help?

The code is modified from here: http://www.yourhomenow.com/house/haversine.html

var p1 = myRectPolygon.getPath().getAt(0);
var p2 = myRectPolygon.getPath().getAt(3);

var lat1 = p1.lat().toRad();
var lat2 = p2.lat().toRad();
var lon1 = p1.lng().toRad();
var dLon = (p2.lng() - p1.lng()).toRad();


var Bx = Math.cos(lat2) * Math.cos(dLon);
var By = Math.cos(lat2) * Math.sin(dLon);
lat3 = Math.atan2(Math.sin(lat1)+Math.sin(lat2),
                  Math.sqrt((Math.cos(lat1)+Bx)*(Math.cos(lat1)+Bx) + By*By ) ); 
lon3 = lon1.toRad() + Math.atan2(By, Math.cos(lat1) + Bx);

var mid_latLng = new google.maps.LatLng(lat3, lon3);
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
user3792705
  • 577
  • 3
  • 18

2 Answers2

1

You are converting lon1 to rad twice:

You declared:

 var lon1 = p1.lng().toRad();

And later you do:

 lon3 = lon1.toRad() + Math.atan2(By, Math.cos(lat1) + Bx);

try changing it to

 lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx);

I also found this solution (Using the Haversine Formula in Javascript) which indicates that doing something like the following may not work correctly

(lon2-lon1).toRad();

and to instead do something like

var dLonDeg = lon2-lon1
var dlon    = dLonDeg.toRad()
Community
  • 1
  • 1
Rob
  • 2,618
  • 2
  • 22
  • 29
1

You can use the geometry library to compute the midpoint:

var p1 = myRectPolygon.getPath().getAt(0);
var p2 = myRectPolygon.getPath().getAt(3);

var mid_latLng = google.maps.geometry.spherical.computeOffset(p1,
     google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 2,
     google.maps.geometry.spherical.computeHeading(p1, p2));

proof of concept fiddle

geocodezip
  • 158,664
  • 13
  • 220
  • 245