Home >Java >javaTutorial >How to Calculate Distance and Create a Bounding Box from Latitude and Longitude?
Measuring Distance and Creating a Bounding Box from Latitude and Longitude
Calculating the distance between two geographical coordinates (latitude and longitude) is essential in various applications, such as mapping and navigation. The great circle distance, also known as the Haversine formula, provides an accurate estimate of the distance between two points along the surface of the earth.
Once the distance is determined, the next step is to define a bounding box around a specific point. This box serves to encapsulate the point within a specific geographical region. To create this box, we need to find the points located at the given distance north and east of the original point.
Java Implementation
The following Java code snippet provides an implementation of the Haversine formula to calculate the distance between two points and create a bounding box:
<code class="java">import java.lang.Math; public class DistanceBoundingBox { public static void main(String[] args) { double lat1 = 37.386051; // Latitude of the origin point double lng1 = -122.083855; // Longitude of the origin point double distance = 10; // Distance in miles to extend the bounding box double lat2 = lat1 + distance / 69; // Calculate the northernmost point double lng2 = lng1 + distance / Math.cos(lat1 / 57.2957795) / 69; // Calculate the easternmost point System.out.println("Distance between the two points: " + distance); System.out.println("North: " + lat2); System.out.println("East: " + lng2); } }</code>
Usage:
Input the latitude and longitude coordinates of two points in the main method. The code will calculate the great circle distance between the points and print it to the console. It will also compute the northernmost and easternmost points that are located at the given distance from the original point.
Additional Considerations:
The above is the detailed content of How to Calculate Distance and Create a Bounding Box from Latitude and Longitude?. For more information, please follow other related articles on the PHP Chinese website!