Search code examples
iosdictionarybuttonswift4google-maps-sdk-ios

How to add button on GMSMapView using swift 4


this is my view controller and it did not work even when i add values to CGRect

import UIKit
import GoogleMaps

class ViewController: UIViewController,CLLocationManagerDelegate, 
GMSMapViewDelegate {

 override func viewDidLoad() {
super.viewDidLoad()

let camera = GMSCameraPosition.camera(withLatitude: 52.649030, 
longitude: 1.174155, zoom: 14)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.delegate = self
self.view = mapView

let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 52.649030, 
longitude: 1.174155)
marker.title = "marker1"
marker.snippet = "city"
marker.map = mapView
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
self.view.addSubview(button)

}

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
 print(marker.position)
 return true
  }
  }

so , is there any mistakes in my code? thank you


Solution

  • There is nothing wrong with your code. The button is actually there. If you inspect the layers, you can see it in the top left corner, like so:

    Simply add button title/title color. or background color and you'll see it. enter image description here

        let button = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
    
    button.setTitle("Button", for: .normal)
    button.setTitleColor(.red, for: .normal)
    button.addTarget(self, action: #selector(handleTap), for: .touchUpInside)
    self.view.addSubview(button)
    
    @objc func handleTap(_ sender: UIButton) {
        print("You tapped a button")
    }
    

    After moving the button and setting title, it will look like this: enter image description here