Kjell-Bear
Kjell-Bear

Reputation: 769

Find coordinate a certain distance and heading away from another coordinate

I am using the Google Maps Geometry Library two calculate both the distance and heading between two points:

...computeDistanceBetween(coord1, coord2) // = 10 m.
...computeHeading(coord1, coord2) // = 25

From this I want to find a point, based on another known coordinate, which is also 10 m. away, in the same direction (heading):

...computeDistanceBetween(coord3, unknown) // = 10 m.
...computeHeading(coord3, unknown) // = 25

How would one go about calculating unknown in this situation?

Upvotes: 0

Views: 797

Answers (1)

geocodezip
geocodezip

Reputation: 161384

Use computeOffset. From the documentation:

computeOffset(from:LatLng, distance:number, heading:number, radius?:number)

Return Value: LatLng

Returns the LatLng resulting from moving a distance from an origin in the specified heading (expressed in degrees clockwise from north).

var distance = google.maps.geometry.spherical.computeDistanceBetween(coord1, coord2);
var heading = google.maps.geometry.spherical.computeHeading(coord1, coord2);
var newPt = google.maps.geometry.spherical.computeOffset(coord1, distance/2, heading);

code snippet:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var coord1 = new google.maps.LatLng(37.399228, -122.208676); // SouthWest corner
  var coord2 = new google.maps.LatLng(37.484548, -122.075124); // NorthEast corner
  var distance = google.maps.geometry.spherical.computeDistanceBetween(coord1, coord2);
  var heading = google.maps.geometry.spherical.computeHeading(coord1, coord2);
  var newPt = google.maps.geometry.spherical.computeOffset(coord1, distance / 2, heading);
  console.log(newPt.toUrlValue(6) + ", distance=" + distance.toFixed(2) + ", heading=" + heading);
  var marker = new google.maps.Marker({
    position: newPt,
    map: map
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_canvas"></div>

Upvotes: 2

Related Questions