由于本次項(xiàng)目 需要在國(guó)外使用,所以最后選取的是使用google地圖,google的地圖怎么導(dǎo)入工程這里就不說了,網(wǎng)上有很多,官網(wǎng)也給出了cocoapods的例子。可能你需要考慮被墻的原因,我這里是使用framework導(dǎo)入的方式,地圖版本 GoogleMaps.1.13.2。
這里說的是一個(gè)關(guān)于谷歌地圖上畫圓的方法,并且符合地圖的縮放層級(jí),圓在地圖上的半徑 ,符合自己設(shè)置的公里數(shù)半徑。
使用百度和高德地圖的時(shí)候,都有簡(jiǎn)單的畫圓方法,but,google沒有,這就坑了,由于我們需要設(shè)置一個(gè)地理圍欄,這個(gè)是需要顯示出來的,中心店和半徑,以及范圍。所以這些東西在地圖上畫出來的時(shí)候需要準(zhǔn)確。
接下來直接說實(shí)現(xiàn)方式:
首先。google 有提供一個(gè)畫任意多邊形的類 GMSPolygon,看樣子我們就從這個(gè)類入手。
思路:1、取得圓中心點(diǎn)(界面點(diǎn)) ->2、使用半徑獲取圓周上的點(diǎn)(界面點(diǎn),這里我們只能畫一個(gè)無限接近圓的多邊形)->3、界面點(diǎn)影射到地圖的經(jīng)緯度點(diǎn)->4、繪畫
思路很簡(jiǎn)單,獲取中心和半徑 這個(gè)自己設(shè)置, 這里的關(guān)鍵在于 如何將界面的點(diǎn)影射到GMSMaps 上。索性 有這個(gè)屬性
/**
* Returns a GMSProjection object that you can use to convert between screen
* coordinates and latitude/longitude coordinates.
*
* This is a snapshot of the current projection, and will not automatically
* update when the camera moves. It represents either the projection of the last
* drawn GMSMapView frame, or; where the camera has been explicitly set or the
* map just created, the upcoming frame. It will never be nil.
*/
@property(nonatomic, readonly) GMSProjection *projection;
這個(gè)屬性解決我們地圖到界面的影射關(guān)系,最開始 我是沒找的的,自己計(jì)算,還要考慮縮放層級(jí),真是苦,所以先看看 屬性 還是有好處的。
@interface GMSProjection?
- (CGPoint)pointForCoordinate:(CLLocationCoordinate2D)coordinate;
- (CLLocationCoordinate2D)coordinateForPoint:(CGPoint)point;
使用的也就這二個(gè)方法 1地圖->界面點(diǎn) ? ? ? 2 界面點(diǎn)->經(jīng)緯度
OK,影射問題解決了,還有個(gè)問題就是計(jì)算圓周上的點(diǎn),
這里直接給大家一個(gè)公式:
circle_x = center_x + r* cos(PI);
circle_y = center_y + r* sin(PI);
我這里是取得60 個(gè)點(diǎn)(注意這里的半徑是米),代碼如下,包括畫圓所有方法都在這里。
GMSMutablePath * path = [[GMSMutablePath alloc]init];
CGFloat xx = 0;
CGFloat yy = 0;
CLLocationCoordinate2D ll;
for (int i = 1; i <= 60; i+=1) { //計(jì)算圓周上的60個(gè)點(diǎn)
xx = point.x + radius*cos(M_PI*2 * (i/60.0));
yy = point.y + radius*sin(M_PI*2 * (i/60.0));
ll = [mapsView.projection coordinateForPoint:CGPointMake(xx, yy)]; //界面點(diǎn)影射到地圖的經(jīng)緯度
[path addCoordinate:ll];
}
if (!polygon) {
polygon = [GMSPolygon polygonWithPath:path];
}else{
[polygon setPath:path];
}
polygon.fillColor = [ThemeColor(@"ihomeStyle") colorWithAlphaComponent:.4];
polygon.strokeColor = ThemeColor(@"ihomeStyle");
polygon.strokeWidth = 1;
polygon.map = mapsView;
最后,由于地球是橢圓形,所以在地圖上,如果你的半徑太大,那么出來的是橢圓 而不是圓, 這個(gè)是地圖針對(duì)地球球面做的優(yōu)化。實(shí)際給的是圓,只是由于球面拉伸成了橢圓。