简体   繁体   中英

Find a point after specific distance in straight line between 2 Points in google maps API

I have a straight line from P1 to P2 as shown below, drawn using google maps API. Latitude and Longitude is available for both of these points.

I want to find a point in between these straight line say (P) with latitude and longitude which is located after some distance from P1.

Eg : Say distance between P1 and P2 is 10 km, I want to find a point located 4 km after P1 in a straight line to P2.

在此处输入图片说明

 function markPointInStraightLine(LatLngP1,LatLngP2, distanceInKm) {
       // To do
       //LatLngP1 and LatLngP2 is of type 'google.maps.LatLng'
}

You can use the interpolate function from the google api geometry library

Given two LatLng objects and value between 0 and 1, you may also calculate a destination between them using the interpolate() method, which performs spherical linear interpolation between the two locations, where the value indicates the fractional distance to travel along the path from the origin to the destination.

more info at google api

I would suggest using the geometry library of Maps JavaScript API. The geometry library provides computeHeading() method to define heading between two points and computeOffset() method to calculate point on the certain distance from an origin in the specified heading. Add &libraries=geometry parameter in Maps JavaScript API URL in order to use the geometry library in your application

The code snippet should be

function markPointInStraightLine(LatLngP1,LatLngP2, distanceInKm) {
    var heading = google.maps.geometry.spherical.computeHeading(LatLngP1,LatLngP2);
    var p = google.maps.geometry.spherical.computeOffset(LatLngP1, distanceInKm*1000, heading);
    return p;
}

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM