배운 것/안드로이드
[안드로이드] 구글맵에서 구멍 뚫린 도넛형 범위 표시하기
ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ!
2021. 10. 9. 14:31
API에서 제공하는 Circle 써서는 불가능한듯.
그래서 Polygon을 사용해서 구현한다.
polygon1은 Polygon객체임.
addAll을 통해 큰 원을 그리고, addHole을 통해 구멍을 내준다.
LatLng SEOUL = new LatLng(37.56, 126.97);
ArrayList<LatLng> big = drawCircle(SEOUL, r2);
ArrayList<LatLng> small = drawCircle(SEOUL, r1);
if (polygon1 != null)
polygon1.remove();
polygon1 = mMap.addPolygon(new PolygonOptions()
.clickable(true)
.addAll(big)
.addHole(small)
.strokeWidth(2)
.strokeColor(getColor(R.color.circle_outter)));
polygon1.setFillColor(getColor(R.color.circle_inner));
drawcircle 메소드. c는 중심점이고 r은 반지름 (m)이다.
단위를 변환하고 싶다면 earth_rad값도 바꾸고 싶은 단위에 맞추어 바꾸어 주여야 함.
private ArrayList<LatLng> drawCircle(LatLng c, int r) {
double d2r = Math.PI / 180;
double r2d = 180 / Math.PI;
double earth_rad = 6378000f; //지구 반지름 근사값
int points = 32; //원(처럼 생긴 다각형)을 그릴 때 쓸 점의 갯수
double rlat = (r / earth_rad) * r2d;
double rlng = rlat / Math.cos(c.latitude * d2r);
ArrayList<LatLng> extp = new ArrayList<>();
for (int i = 0; i < points + 1; i += 1) {
double theta = Math.PI * (i / ((double) points / 2));
double y = c.longitude + (rlng * Math.cos(theta));
double x = c.latitude + (rlat * Math.sin(theta));
extp.add(new LatLng(x, y));
}
return extp;
}
아무래도 지구 평균 반지름을 기반으로 한 계산이다 보니 오차가 있다.
(밖 : drawCircle 메소드, 안 : 구글맵 Circle API사용)
원본 소스 : http://www.geocodezip.com/v3_polygon_example_donut.html
(자바스크립트 코드를 자바로 변환하였음.)