지도에서 많은 이벤트를 보여주고 싶은 앱을 개발 중입니다. 사용자는 이벤트를 클릭하여 이벤트에 대한 많은 정보를 볼 수 있습니다. 다른보기에서, 사용자는 새로운 이벤트를 생성 할 수 있으며 그 다음 위치와 제목은 Firebase 데이터베이스에 저장됩니다. 그러면 다른 사용자가 내 앱에서 Google지도를 볼 때지도의 마커 인 모든 이벤트를 볼 수 있습니다. 사용자가 맵에서 축소 할 때 Firebase에서 마커를 클러스터링하려고하지만 Firebase의로드 된 데이터 마커로 인해 작동하지 않을 수 있습니다. 다음과 같은 세 가지 문제가 있습니다. - 사용자 지정 마커를 주황색으로 클러스터 할 수 없습니다. -지도가로드 될 때 마커 및 클러스터 아이콘이 나타나지 않습니다. 먼저 확대하거나 축소해야합니다. - 마커의 데이터를 infoWindow에 표시하고 싶습니다. 마커에 올바른 데이터를 사용해야합니다. GoogleMap 및 Firebase에 해당합니다. - 클러스터 아이콘을 클릭하면 alertController도 표시되지만 클러스터 아이콘이 아닌 마커를 탭하면 alertController 만 보입니다.iOS 용 GoogleMaps에서 Firebase의 마커를 클러스터하는 방법
여기에 내 현재 코드입니다 :
class POIItem: NSObject, GMUClusterItem {
var position: CLLocationCoordinate2D
var name: String!
init(position: CLLocationCoordinate2D, name: String) {
self.position = position
self.name = name
}
}
class NewCarteViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate, GMUClusterManagerDelegate {
var locationManager = CLLocationManager()
var positionActuelle = CLLocation() // Another current position
var currentPosition = CLLocationCoordinate2D()
var latiti: CLLocationDegrees!
var longiti: CLLocationDegrees!
private var clusterManager: GMUClusterManager! // Cluster
private var maMap: GMSMapView!
var marker = GMSMarker()
let geoCoder = CLGeocoder()
var ref = DatabaseReference()
var estTouche: Bool!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
positionActuelle = locationManager.location!
latiti = positionActuelle.coordinate.latitude
longiti = positionActuelle.coordinate.longitude
currentPosition = CLLocationCoordinate2D(latitude: latiti, longitude: longiti)
let camera = GMSCameraPosition.camera(withTarget: currentPosition, zoom: 10)
maMap = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
maMap.mapType = .normal
maMap.settings.compassButton = true
maMap.isMyLocationEnabled = true
maMap.settings.myLocationButton = true
maMap.delegate = self
self.view = maMap
let iconGenerator = GMUDefaultClusterIconGenerator()
let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
let renderer = GMUDefaultClusterRenderer(mapView: maMap, clusterIconGenerator: iconGenerator)
clusterManager = GMUClusterManager(map: maMap, algorithm: algorithm, renderer: renderer)
loadMarker()
}
// Download datas of markers from Firebase Database
func loadMarker() {
ref = Database.database().reference()
let usersRef = ref.child("markers")
usersRef.observeSingleEvent(of: .value, with: { (snapshot) in
if (snapshot.value is NSNull) {
print("not found")
} else {
for child in snapshot.children {
let userSnap = child as! DataSnapshot
let uid = userSnap.key // the uid of each user
let userDict = userSnap.value as! [String: AnyObject]
let latitudes = userDict["latitudeEvent"] as! Double
let longitudes = userDict["longitudeEvent"] as! Double
let bellname = userDict["nom"] as! String
let belltitre = userDict["titreEvent"] as! String
let total = snapshot.childrenCount // Number of markers in Firebase
let positionMarker = CLLocationCoordinate2DMake(latitudes, longitudes)
var diff = Double(round(100*self.getDistanceMetresBetweenLocationCoordinates(positionMarker, coord2: self.currentPosition))/100)
var dif = Double(round(100*diff)/100)
var positionEvenement = CLLocation(latitude: latitudes, longitude: longitudes) // Event location
// Function in order to convert GPS Coordinate in an address
CLGeocoder().reverseGeocodeLocation(positionEvenement, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder a rencontré une erreur " + (error?.localizedDescription)!)
return
}
if (placemarks?.count)! > 0 {
print("PlaceMarks \(placemarks?.count)!")
let pm = placemarks?[0] as! CLPlacemark
var adres = "\(pm.name!), \(pm.postalCode!) \(pm.locality!)"
let item = POIItem(position: CLLocationCoordinate2DMake(latitudes, longitudes), name: "")
// self.marker.userData = item // I delete this line
self.clusterManager.add(item)
self.marker = GMSMarker(position: positionMarker)
self.marker.icon = UIImage(named: "marker-45")
self.marker.title = "\(belltitre)"
self.marker.snippet = "Live de \(bellname)\nLieu: \(adres)\nDistance: \(dif) km"
self.marker.map = self.maMap
} else {
print("Problème avec les données reçu par le géocoder")
}
})
}
self.clusterManager.cluster()
self.clusterManager.setDelegate(self, mapDelegate: self)
}
})
}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
if let poiItem = marker.userData as? POIItem {
NSLog("Did tap marker for cluster item \(poiItem.name)")
} else {
NSLog("Did tap a normal marker")
}
return false
}
func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool {
let newCamera = GMSCameraPosition.camera(withTarget: cluster.position, zoom: maMap.camera.zoom + 1)
let update = GMSCameraUpdate.setCamera(newCamera)
maMap.moveCamera(update)
return false
}
func renderer(_ renderer: GMUClusterRenderer, markerFor object: Any) -> GMSMarker? {
let marker = GMSMarker()
if let model = object as? POIItem { // POIItem class is your MarkerModel class
marker.icon = UIImage(named: "marker-45") // Like this ?
// set image view for gmsmarker
}
return marker
}
// Distance between 2 locations
func getDistanceMetresBetweenLocationCoordinates(_ coord1: CLLocationCoordinate2D, coord2: CLLocationCoordinate2D) -> Double {
let location1 = CLLocation(latitude: coord1.latitude, longitude: coord1.longitude)
let location2 = CLLocation(latitude: coord2.latitude, longitude: coord2.longitude)
var distance = ((location1.distance(from: location2))/1000)
return distance
}
// Affiche les boutons du live
func alert(_ sender: AnyObject) {
let alertController = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
alertController.title = nil
alertController.message = nil
alertController.addAction(UIAlertAction(title: "Accéder au live", style: .default, handler: self.accederLive))
alertController.addAction(UIAlertAction(title: "Infos event", style: .default, handler: self.infosEvent))
alertController.addAction(UIAlertAction(title: "Annuler", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
// Display infoWindow and alertController
func mapView(_ mapView: GMSMapView!, markerInfoWindow marker: GMSMarker!) -> UIView! {
let infoWindow = Bundle.main.loadNibNamed("InfoWindow", owner: self, options: nil)?.first! as! CustomInfoWindow
self.estTouche = true
if self.estTouche == true {
self.alert(self.estTouche as AnyObject)
} else {
print("estTouche est false")
}
print(self.estTouche)
return nil // infoWindow
}
미안해 릴 비트 긴 코드 당신이 뭔가 내가
여기 지금 GoogleMap으로의 스크린 샷의 언급을했는데, 알려 이해하지 않는 경우.
첫 번째 스크린 샷은 내가지도를 열 때, 당신은 아무것도지도, 아니 클러스터 아이콘 또는 분리 마커, 이상한에 나타납니다 볼 수 있습니다.
두 번째 스크린 샷은 한 번 확대하면 클러스터 아이콘이 나타나고 하나의 표식이 나타납니다. 내 코드가 잘못되었으므로 사용자가지도보기를 열 때 모든 클러스터 아이콘이나 마커 쇼가 필요합니다. 첫째 loadMarker()
는 clusterManager 후에 호출되어야
가 좋아 난 당신의 조언 순서와 내 게시물을 편집
나는 마지막으로 (너무 그것을 할 사람을 도울 수 있다면) 다른 스위프트 파일에 중포 기지에서 마커의 데이터를로드하는 내 방식 추가 그것이 제대로 작동하지 않기 때문에 내가 옳은지 확인하기 위해 –
어떤 오류가 발생했는지 또는 어떤 일이 일어 났는지 스크린 샷을 게시 할 수 있는지 알려주시겠습니까 –
예 이미지로 내 게시물을 업데이트하면 클러스터 이미지가 표시됩니다. Firebase에서 마커를 숨기면 맵상에 두 개의 마커가 있습니다 (파리에는 여섯 개의 마커가 있습니다)하지만 클러스터 아이콘의 수는 10+이므로 코드를 실행하지 않을 때 2 개의 오류가 발생하여 앱이 잘못 표시됩니다 –