How to get Google Map

Pre Requirement : 

Also Want to Create a Custom Cell Marker.

pod installs :

# AlamoFire
pod 'Alamofire'
# SwiftyJson
    pod 'SwiftyJSON'
    
# google Maps
    pod 'GoogleMaps'
    pod 'GooglePlaces'
    pod 'GooglePlacePicker'

Import :

import GoogleMaps

import SwiftyJSON

Protocols To Call : 

   CLLocationManagerDelegate   // get Location 
   GMSMapViewDelegate          // Google Map

      GetLocationPlaces    // custom Protocol for get the Location Function


Generic Class :


protocol GetLocationPlaces {
    
    func successResponseForPlacesAPI(_ objResponse: [String : AnyObject])
    func errorResponseForPlacesAPI(_ error:String)  }

class APIManager: NSObject {
     
   var placesDelegate              : GetLocationPlaces?

func locationPlaces(PlacesParam : String){
        
        guard Connectivity.isConnectedToInternet() else {
            self.logInDelegate?.errorResponseForLogInAPI(kNonetworkfound)
            return
        }
        
        let  url = APIConfig.googlePlaceURL + APIConfig.googlePlaceKeyword + PlacesParam + APIConfig.googlePlaceKey
        
        Alamofire.request(url).responseJSON { (response : DataResponse<Any>) in
            
            switch(response.result) {
            case .success(_):
                
                if let JSONData = response.result.value{
                    let json = try! JSON(data: response.data!)
                    print(json)
                    
                    self.placesDelegate?.successResponseForPlacesAPI(JSONData as! [String : AnyObject])
                }
                
                break
                
            case .failure(_):
                print("fail")
                break
            }
            
        }
        
    }


ViewControl Functions :

@IBOutlet weak var mapView: GMSMapView!
    var locationManager = CLLocationManager()
    let API = APIManager()
    var json : JSON!
    var states : State! = nil
    var Addmarker: GMSMarker?

override func viewDidLoad() {
        super.viewDidLoad()
        
        loadViewInUIView()
        
        API.placesDelegate = self
    }

func loadViewInUIView() {
        
        // Create a GMSCameraPosition that tells the map to display the
        // coordinate -33.86,151.20 at zoom level 6.
        let camera = GMSCameraPosition.camera(withLatitude: GlobalLat, longitude: GlobalLong, zoom: 17.0)
        self.mapView.camera = camera
        mapView.delegate = self
        self.mapView.isMyLocationEnabled = true
        
        // Creates a marker in the center of the map.
        
        let initialLocation = CLLocationCoordinate2D(latitude: GlobalLat, longitude: GlobalLong)
        let marker = GMSMarker(position: initialLocation)
        
        self.getLogationAddress(lat: GlobalLat, long: GlobalLong) { Address in
        
            marker.title = "Address"
            marker.snippet = Address
            self.Addmarker = marker
       }
        
        marker.map = mapView
        
        do {
            // Set the map style by passing a valid JSON string.
            mapView.mapStyle = try GMSMapStyle(jsonString: kMapStyle)
        } catch {
            NSLog("One or more of the map styles failed to load. \(error)")
        }
        
    }


@IBAction func Origen(_ sender: Any) {
        self.ClearMarkers()
        //Your map initiation code
//        let camera = GMSCameraPosition.camera(withLatitude: 23.931735,longitude: 121.082711, zoom: 7)
//        self.mapView.camera = camera
       
        self.mapView?.isMyLocationEnabled = true
        //Location Manager code to fetch current location
        self.locationManager.delegate = self
        self.locationManager.startUpdatingLocation()
    }
    
    @IBAction func hospital(_ sender: Any) {
        API.locationPlaces(PlacesParam: "Hospital")
    }

    
    @IBAction func ClearMarksAction(_ sender: Any) {
        self.ClearMarkers()
    }
    
    
    //Location Manager delegates
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        let location = locations.last
        
        let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0)
        
        self.mapView?.animate(to: camera)
        
        //Finally stop updating location otherwise it will come again and again in this delegate
        self.locationManager.stopUpdatingLocation()
        
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error \(error)")
    }
    
    // Just For Sample Remove After Completion of Project
    func setMarkersinMap(lat : Double, long : Double, Title : String){
        
        let camera = GMSCameraPosition.camera(withLatitude: GlobalLat, longitude: GlobalLong, zoom: 12)
        self.mapView.camera = camera
        
        let initialLocation = CLLocationCoordinate2DMake(lat, long)
        let marker = GMSMarker(position: initialLocation)
        marker.title = Title
        marker.map = mapView
    }
    
    func ClearMarkers(){
        self.mapView.clear()
    }
    
    // Based on Loaction Get the exact placemarks Value
    func getLogationAddress(lat : Double, long : Double, handler: @escaping (String) -> Void){
        
        var address: String = ""
        let geoCoder = CLGeocoder()
        
        let location = CLLocation(latitude: lat, longitude: long)
        //selectedLat and selectedLon are double values set by the app in a previous process
        
        geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
            
            // Place details
            var placeMark: CLPlacemark?
            placeMark = placemarks?[0]
            
            // Location name
            if let locationName = placeMark?.name {
                address += locationName + ", "
            }
            
            // Street address
            if let street = placeMark?.thoroughfare {
                address += street + ", "
            }
            
            // City
            if let city = placeMark?.locality  {
                address += city + ", "
            }
            
            // Zip code
            if let zip = placeMark?.postalCode {
                address += zip + ", "
            }
            
            // Country
            if let country = placeMark?.country {
                address += country
            }
            
            // Passing address back
            handler(address)
        })
    }
    
}

// For custom Pin Info View
extension MapPlacesVC: GMSMapViewDelegate {
    
    func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
       
        let customInfoWindow = Bundle.main.loadNibNamed("MapPlaceMarkerInfoXIB", owner: self, options: nil)?[0] as! MapPlaceMarkerInfoView
        customInfoWindow.nameLabel.text  = marker.title
        customInfoWindow.placePhoto.image = marker.icon
        
        
      //  customInfoWindow.placePhoto.image = UIImage(named: "\(marker.icon ?? imagePlaceHolderURL)")
        
       return customInfoWindow
            }
    
}

extension MapPlacesVC : GetLocationPlaces{
    
    func successResponseForPlacesAPI(_ objResponse: Dictionary<String, AnyObject>) {
        print(objResponse)
       
        json = JSON(objResponse as [String : AnyObject])
        print(json)
        
        print(json["results"].count)
       
        ClearMarkers()

        
        for i in 0...json["results"].count{
            
            let lat = json["results"][i]["geometry"]["location"]["lat"].doubleValue
            let long = json["results"][i]["geometry"]["location"]["lng"].doubleValue
            let title = json["results"][i]["name"].stringValue
            let icon = json["results"][i]["icon"].stringValue
            
          //    self.setMarkersinMap(lat: lat, long: long, Title: title)
            
        //    states = State.init(name: title, long: lat, lat: long)
            
          //  let camera = GMSCameraPosition.camera(withLatitude: GlobalLat, longitude: GlobalLong , zoom: 12)
           // self.mapView.camera = camera
            mapView.delegate = self
            let initialLocation = CLLocationCoordinate2DMake( lat,long)
            let marker = GMSMarker(position: initialLocation)
                marker.title = title
                marker.map = mapView
           
            DispatchQueue.main.async {
                if icon != ""
                {
                    let url = URL(string: icon)
                    let data = try? Data(contentsOf: url!)
                    marker.icon  = UIImage(data: data!)
                    
                    //  marker.icon = UIImage(named: icon)
                }
               
            }
            self.Addmarker = marker
        }
        
        
    }
    
    func errorResponseForPlacesAPI(_ error: String) {
        print(error)
    }
    
}











Comments