user3792705
user3792705

Reputation: 617

How to find middle point of a line in google map

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);

Upvotes: 1

Views: 887

Answers (2)

geocodezip
geocodezip

Reputation: 161324

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

Upvotes: 1

Rob
Rob

Reputation: 2656

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()

Upvotes: 1

Related Questions