구글 맵에 커스텀 마커 표시하기
받아온 데이터의 위도, 경도 정보를 이용해 지도 상에 마커를 찍고 싶은 데 구글에서 제공하는 마커는 디자인이 너무 별로라 마커를 커스텀해봤습니다.
아래 사진과 같이 받아온 데이터 index를 표시하는 마커를 구현했습니다.
마커를 표시할 때는 이미지뷰를 사용하기 때문에 표시하고자 하는 마커 모양의 이미지가 필요합니다.
저는 아래 사진과 같은 모양의 마커를 사용했고, 인덱스를 표시하는 이미지는 SF Symbol 이미지를 사용했습니다.
사용한 open Api의 데이터가 일정하지 않아 좌표가 있는 경우에만 마커를 표시하도록 했습니다.
//create Maker
DispatchQueue.main.async {
self.restaurantData?.enumerated().forEach({ (index, data) in
if !data.xposition.isEmpty && !data.yposition.isEmpty {
let numImage = UIImage(systemName: "\(index).circle.fill")
let markerImage = UIImage(named: "marker")?.withTintColor(.gray)
let location = CLLocation(latitude: Double(data.xposition)!, longitude: Double(data.yposition)!)
let marker = GMSMarker(position: location.coordinate)
marker.icon = drawImageWithNumberPic(numImg: numImage!, image: markerImage!)
marker.appearAnimation = GMSMarkerAnimation.pop
marker.map = self.googleMapView
}
})
}
func drawImageWithNumberPic(numImg: UIImage, image: UIImage) -> UIImage {
let imgView = UIImageView(image: image)
imgView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
let numberView = UIImageView(image: numImg)
numberView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
numberView.tintColor = .white
imgView.addSubview(numberView)
numberView.center.x = imgView.center.x
numberView.center.y = imgView.center.y - 7
numberView.clipsToBounds = true
imgView.setNeedsLayout()
numberView.setNeedsLayout()
let newImage = imageWithView(view: imgView)
return newImage
}
//지정된 옵션을 사용하여 비트맵 기반 그래픽 컨텍스트를 만들어줍니다.
func imageWithView(view: UIView) -> UIImage {
var image: UIImage?
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
if let context = UIGraphicsGetCurrentContext() {
view.layer.render(in: context)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
return image ?? UIImage()
}
원래 사용하려던 Api의 데이터는 위도,경도가 아니라 좌표를 제공해서 사용할 수 없었습니다...😭
GMSCameraPosition 을 이용할 때 CLLocation을 사용하는 데 CLLocation에서 x,y 좌표를 사용하는 방법을 찾지 못했습니다.
혹시 아시는 분은 댓글 달아주시면 감사하겠습니다!!

'개발 > iOS' 카테고리의 다른 글
[iOS] 웹뷰를 활용해 HTML 콘텐츠 화면에 출력하기 (0) | 2023.01.26 |
---|---|
[iOS][Swift] 세자리 콤마 넣기 (0) | 2023.01.25 |
iOS 스토리보드(Storyboard) components 정리하기 (0) | 2023.01.19 |
[iOS] 카카오 소셜 간편 로그인( kakao login) API 연동 (0) | 2023.01.19 |
[iOS] Google Map Api 구글 지도 마커 사용자 위치 적용하기 (1) | 2023.01.19 |