這是一個完整的Java類,用於指定邊界框並檢查點是否位於其中。該框由其西南和東北地理座標(經度和緯度)定義。
class Bbox
{
public double swLatitude = 0.0;
public double swLongitude = 0.0;
public double neLatitude = 0.0;
public double neLongitude = 0.0;
/*************************************************************************
Constructor.
@param bboxSpecification A comma-separated string containing the
southwest latitude, soutwest longitude, northest latitude, and
northest longitude.
*************************************************************************/
public Bbox(String bboxSpecification)
{
String tokens[] = bboxSpecification.split("(?:,\\s*)+");
if (tokens.length != 4)
{
throw new IllegalArgumentException(
String.format("Expected 4 values in bbox string but found %d: %s\n",
tokens.length, bboxSpecification));
}
swLatitude = Double.parseDouble(tokens[0]);
swLongitude = Double.parseDouble(tokens[1]);
neLatitude = Double.parseDouble(tokens[2]);
neLongitude = Double.parseDouble(tokens[3]);
}
@Override
public String toString()
{
return String.format("swLatitude=%f, swLongitude=%f, neLatitude=%f, neLongitude=%f",
swLatitude, swLongitude, neLatitude, neLongitude);
}
/*************************************************************************
Checks if the bounding box contains the latitude and longitude. Note that
the function works if the box contains the prime merdian but does not
work if it contains one of the poles.
*************************************************************************/
public boolean contains(double latitude, double longitude)
{
boolean longitudeContained = false;
boolean latitudeContained = false;
// Check if the bbox contains the prime meridian (longitude 0.0).
if (swLongitude < neLongitude)
{
if (swLongitude < longitude && longitude < neLongitude)
{
longitudeContained = true;
}
}
else
{
// Contains prime meridian.
if ((0 < longitude && longitude < neLongitude) ||
(swLongitude < longitude && longitude < 0))
{
longitudeContained = true;
}
}
if (swLatitude < neLatitude)
{
if (swLatitude < latitude && latitude < neLatitude)
{
latitudeContained = true;
}
}
else
{
// The poles. Don't care.
}
return (longitudeContained && latitudeContained);
}
public static void test()
{
Bbox bbox;
double latitude = 0;
double longitude = 0;
bbox = new Bbox("37.43, -122.38, 37.89, -121.98");
latitude = 37.5;
longitude = -122.0;
System.out.printf("bbox (%s) contains %f, %f: %s\n",
bbox, latitude, longitude, bbox.contains(latitude, longitude));
bbox = new Bbox("50.99, -2.0, 54, 1.0");
latitude = 51.0;
longitude = 0.1;
System.out.printf("bbox (%s) contains %f, %f: %s\n",
bbox, latitude, longitude, bbox.contains(latitude, longitude));
}
}
注意到@下面zeisemer的答案,你的方式措辭你的問題(有兩個邊界點),一種限制你的「地圖」,以作爲一個簡單的線條。如果你想指定一個多維度的區域,那麼你至少需要三點,比如奧蘭多,芝加哥和紐約。 – 2011-12-17 03:20:14
@Tom我以爲他在談論一個邊框 – Dev 2011-12-17 03:22:47
你問的只是如何找出一個點是否在矩形內。這已經被覆蓋了很多次,遍及這個網站和其他網站。 – Thor84no 2011-12-17 03:28:51