I got some markers in Google Maps and show them with JSON in on map. There is a custom info view as UIView to show some information in it but I can't show json in custom info view labels. Also markers work correctly. I try to use data provider to save data and use it in didTapMarker Method but I can't handle it.
This is the viewController:
class maappp: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: GMSMapView!
var tappedMarker = GMSMarker()
var infoWindow = CustomInfoWindow(frame: CGRect(x: 0, y: 0, width: 300, height: 165))
struct Lugares : Codable {
let latitude : String?
let longitude : String?
let name : String?
let address : String?
let phone : String?
}
private var marcadores = [Lugares]()
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
let cameraZone = GMSCameraPosition.camera(withLatitude: 35.688272, longitude: 51.386217, zoom: 11.0)
mapView.camera = cameraZone
let mapView = GMSMapView.map(withFrame: self.mapView.frame, camera: cameraZone)
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
mapView.settings.compassButton = true
mapView.settings.indoorPicker = true
mapView.settings.scrollGestures = true
mapView.settings.zoomGestures = true
self.tappedMarker = GMSMarker()
guard let mapUrl = URL(string: LOCATION_BASE_URL) else { return }
URLSession.shared.dataTask(with: mapUrl) { (data, response, error) in
if error == nil {
do {
self.marcadores = try JSONDecoder().decode([Lugares].self, from: data!)
DispatchQueue.main.async {
for state in self.marcadores {
print(state.latitude!, state.name!)
let lat = Double(state.latitude!)
let long = Double(state.longitude!)
//markers work correctly
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(
latitude: lat!,
longitude: long!)
marker.map = self.mapView
marker.icon = UIImage(named: "place")
}
}
} catch let jsonError{
print("An error occurred + \(jsonError)")
}
}
}.resume()
}
class func instanceFromNib() -> CustomInfoWindow {
return UINib(nibName: "CustomInfoWindow", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomInfoWindow }
question is how to put recived data from json in 2 below label and
show theme when clicked on a marker
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
let location = CLLocationCoordinate2D(latitude: marker.position.latitude, longitude: marker.position.longitude)
self.tappedMarker = marker
self.infoWindow.removeFromSuperview()
self.infoWindow = maappp.instanceFromNib()
self.infoWindow.nameLbl.text = ""
self.infoWindow.AddressLbl.text = ""
self.infoWindow.center = mapView.projection.point(for: location)
self.view.addSubview(self.infoWindow)
return false
}
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
let location = CLLocationCoordinate2D(latitude: tappedMarker.position.latitude, longitude: tappedMarker.position.longitude)
infoWindow.center = mapView.projection.point(for: location)
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
infoWindow.removeFromSuperview() }
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
return UIView()
}
}
This is the JSON array:
[
{
name: "name1",
longitude: "51.395836",
latitude: "35.776441",
address: "address1",
phone : "57767000"
},
{
name: "name2",
longitude: "51.247014",
latitude: "35.753798",
address: "address2",
phone : "66341933"
},
{
name: "name3",
longitude: "51.243728",
latitude: "35.755143",
address: "address3",
phone : "88887588"
}
]
Related
I am new in iOS and I implemented a MapKit with static markers from different arrays types and they are working fine , I am trying to put pins that come from shops array to be blue for example , and pins that come from community read , etc .. I have no idea about how to do this
at all , they are all in red in the map and my goal is to change the color for every array of pins
here what I have tried :
import UIKit
import MapKit
class myMapViewController: UIViewController, MKMapViewDelegate {
var shops = [Shops]()
var communities = [Community]()
var cyclists = [Cyclist]()
var circuits = [Circuit]()
#IBOutlet weak var myMap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
shops.append(Shops(id: 0, title: "Shop1", latitude: 36.553015 , longitude: 10.592774))
shops.append(Shops(id: 0, title: "Shop2", latitude: 35.499414 , longitude: 10.824846))
communities.append(Community(id: 0, title: "community1", latitude: 37.276943 , longitude: 10.934709 ))
communities.append(Community(id: 0, title: "community2", latitude: 35.427828 , longitude: 9.748186 ))
circuits.append(Circuit(id: 0, title: "circuit1", latitude: 33.773035 , longitude: 10.857805 ))
cyclists.append(Cyclist(id: 0, title: "cyclist1", latitude: 35.785118 , longitude: 10.000871 ))
createShopsAnnotations(locations: shops)
createCircuitsAnnotations(locations: circuits)
createCommunityAnnotations(locations: communities)
createCyclistsAnnotations(locations: cyclists)
}
func createShopsAnnotations(locations:[Shops]){
for location in locations {
let annotations = MKPointAnnotation()
annotations.title = location.title as? String
annotations.coordinate = CLLocationCoordinate2D(latitude: location.latitude as! CLLocationDegrees , longitude: location.longitude as! CLLocationDegrees)
myMap.addAnnotation(annotations)
}
}
func createCircuitsAnnotations(locations:[Circuit]){
for location in locations {
let annotations = MKPointAnnotation()
annotations.title = location.title as? String
annotations.coordinate = CLLocationCoordinate2D(latitude: location.latitude as! CLLocationDegrees , longitude: location.longitude as! CLLocationDegrees)
myMap.addAnnotation(annotations)
}
}
func createCommunityAnnotations(locations:[Community]){
for location in locations {
let annotations = MKPointAnnotation()
annotations.title = location.title as? String
annotations.coordinate = CLLocationCoordinate2D(latitude: location.latitude as! CLLocationDegrees , longitude: location.longitude as! CLLocationDegrees)
myMap.addAnnotation(annotations)
}
}
func createCyclistsAnnotations(locations:[Cyclist]){
for location in locations {
let annotations = MKPointAnnotation()
annotations.title = location.title as? String
annotations.coordinate = CLLocationCoordinate2D(latitude: location.latitude as! CLLocationDegrees , longitude: location.longitude as! CLLocationDegrees)
myMap.addAnnotation(annotations)
}
}
}
I have headed some tutorials but I was not able to apply them on my example.
The basic idea is to make an annotation view type to render the correct color. So, assume for a second that you have four annotation types (see below), then you might have an annotation view type like so:
class AnnotationView: MKMarkerAnnotationView {
override var annotation: MKAnnotation? { didSet { update(for: annotation) } }
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
update(for: annotation)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func update(for annotation: MKAnnotation?) {
switch annotation {
case is Shop: markerTintColor = .blue
case is Community: markerTintColor = .cyan
case is Cyclist: markerTintColor = .green
case is Circuit: markerTintColor = .red
default: break
}
}
}
And then you would have your view controller register that annotation view for your map view:
override func viewDidLoad() {
super.viewDidLoad()
mapView.register(AnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
...
}
Note, when you register an annotation view type like this, you do not want to implement any mapView(_:viewFor:) method. Since iOS 11, that delegate method is not needed/recommended any more.
Anyway, that annotation view type assumes you have four types of annotations. I'd personally make Shop, Community, Cyclist and Circuit just be annotation types, e.g.
class Shop: NSObject, MKAnnotation {
let id: Int
dynamic var title: String?
dynamic var subtitle: String?
dynamic var coordinate: CLLocationCoordinate2D
init(id: Int, title: String, subtitle: String? = nil, coordinate: CLLocationCoordinate2D) {
self.id = id
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
super.init()
}
}
// repeat for the other three types
And then, when I want to add them to my map:
shops.append(Shop(id: 0, title: "Shop1", coordinate: CLLocationCoordinate2D(latitude: 36.553015, longitude: 10.592774)))
shops.append(Shop(id: 0, title: "Shop2", coordinate: CLLocationCoordinate2D(latitude: 35.499414 , longitude: 10.824846)))
communities.append(Community(id: 0, title: "community1", coordinate: CLLocationCoordinate2D(latitude: 37.276943 , longitude: 10.934709)))
communities.append(Community(id: 0, title: "community2", coordinate: CLLocationCoordinate2D(latitude: 35.427828 , longitude: 9.748186)))
circuits.append(Circuit(id: 0, title: "circuit1", coordinate: CLLocationCoordinate2D(latitude: 33.773035 , longitude: 10.857805)))
cyclists.append(Cyclist(id: 0, title: "cyclist1", coordinate: CLLocationCoordinate2D(latitude: 35.785118 , longitude: 10.000871)))
mapView.addAnnotations(shops + communities + circuits + cyclists)
Alternatively, you might have one annotation type:
enum PlaceType {
case shop, community, cyclist, circuit
}
class Place: NSObject, MKAnnotation {
let id: Int
let type: PlaceType
dynamic var title: String?
dynamic var subtitle: String?
dynamic var coordinate: CLLocationCoordinate2D
init(id: Int, type: PlaceType, title: String, subtitle: String? = nil, coordinate: CLLocationCoordinate2D) {
self.id = id
self.type = type
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
super.init()
}
}
You'd then instantiate these places:
var places = [Place]()
override func viewDidLoad() {
super.viewDidLoad()
mapView.register(AnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
places = [
Place(id: 0, type: .shop, title: "Shop1", coordinate: CLLocationCoordinate2D(latitude: 36.553015, longitude: 10.592774)),
Place(id: 0, type: .shop, title: "Shop2", coordinate: CLLocationCoordinate2D(latitude: 35.499414 , longitude: 10.824846)),
Place(id: 0, type: .community, title: "community1", coordinate: CLLocationCoordinate2D(latitude: 37.276943 , longitude: 10.934709)),
Place(id: 0, type: .community, title: "community2", coordinate: CLLocationCoordinate2D(latitude: 35.427828 , longitude: 9.748186)),
Place(id: 0, type: .circuit, title: "circuit1", coordinate: CLLocationCoordinate2D(latitude: 33.773035 , longitude: 10.857805)),
Place(id: 0, type: .cyclist, title: "cyclist1", coordinate: CLLocationCoordinate2D(latitude: 35.785118 , longitude: 10.000871))
]
mapView.addAnnotations(places)
}
And your annotation view type would then use this type parameter:
class AnnotationView: MKMarkerAnnotationView {
override var annotation: MKAnnotation? { didSet { update(for: annotation) } }
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
update(for: annotation)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func update(for annotation: MKAnnotation?) {
guard let annotation = annotation as? Place else { return }
switch annotation.type {
case .shop: markerTintColor = .blue
case .community: markerTintColor = .cyan
case .cyclist: markerTintColor = .green
case .circuit: markerTintColor = .red
}
}
}
This results in:
I assign some value to show marker in google maps. When I click the marker I want to pass the data of this marker assign value to another Controller.
class MapsViewController: UIViewController {
var title_map : String = ""
#IBOutlet weak var googleMapsview: GMSMapView!
var geosearch : [Geosearch]?
private var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// self.map_api_call()
// self.barDesign()
googleMapsview.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
markNearArea()
}
func markNearArea(){
for index in 1...(geosearch?.count)! {
let lat = geosearch?[index-1].lat
let long = geosearch?[index-1].lon
let coordinate = CLLocationCoordinate2D(latitude: lat! , longitude: long!)
let locationMarker = GMSMarker(position: coordinate)
locationMarker.map = self.googleMapsview
locationMarker.title = geosearch?[index-1].title
locationMarker.appearAnimation = .pop
locationMarker.icon = UIImage(named: "map_br.png")
locationMarker.opacity = 1
}
}
}
I want to click marker and want to pass geosearch[position]
extension MapsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool
{
let url = "https://abk.com/?loc=\(String(describing: geosearch![marker.].pageid!))"
if let url = URL(string: url ), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
return true
}
}
You can get a marker position by this
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
let position = marker.position
return true
}
Or if you want other data then use the userData property of GMSMarker. like this
First assign data to marker :
locationMarker.userData = //Assign your any type of data
And inside the delegate
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
let position = marker.position
let markerData = marker.userData // Your marker data
return true
}
I would like to take a screenshot of ongoing VideoCaptureView during a call in iOS Swift. I used QuickBlox.
I have used below code that return black image
public extension UIView {
public func snapshotImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque,0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snapshotImage
}
public func snapshotView() -> UIView? {
if let snapshotImage = snapshotImage() {
return UIImageView(image: snapshotImage)
} else {
return nil
}
}
}
let snapshot = view.snapshotView()
Try this
fileprivate func captureUIImageFromUIView(_ view:UIView?) -> UIImage {
guard (view != nil) else{
// if the view is nil (it's happened to me) return an alternative image
let errorImage = UIImage(named: "Logo.png")
return errorImage!
}
// if the view is all good then convert the image inside the view to a uiimage
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(size: view!.bounds.size)
let capturedImage = renderer.image {
(ctx) in
view!.drawHierarchy(in: view!.bounds, afterScreenUpdates: true)
}
return capturedImage
} else {
UIGraphicsBeginImageContextWithOptions((view!.bounds.size), view!.isOpaque, 0.0)
view!.drawHierarchy(in: view!.bounds, afterScreenUpdates: false)
let capturedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return capturedImage!
}
}
Call
let pdfImage = self.captureUIImageFromUIView(self.containerView)
//
// ViewController.swift
// GooglePlace-AutoComplete
//
// Created by infos on 7/10/18.
// Copyright © 2018 infos. All rights reserved.
//
import UIKit
import GoogleMaps
import GooglePlaces
import SwiftyJSON
import Alamofire
enum Location {
case startLocation
case destinationLocation
}
class ViewController: UIViewController , GMSMapViewDelegate , CLLocationManagerDelegate,UITextFieldDelegate {
#IBOutlet weak var googleMaps: GMSMapView!
#IBOutlet weak var startLocation: UITextField!
#IBOutlet weak var destinationLocation: UITextField!
var locationManager = CLLocationManager()
var locationSelected = Location.startLocation
var polyline = GMSPolyline()
var locationStart = CLLocation()
var locationEnd = CLLocation()
override func viewDidLoad() {
super.viewDidLoad()
GMSPlacesClient.provideAPIKey("AIzaSyC55Dq1qPH7EM_uiAVf-8QuxJtf2W1viQs")
GMSServices.provideAPIKey("AIzaSyC55Dq1qPH7EM_uiAVf-8QuxJtf2W1viQs")
// Create a GMSCameraPosition that tells the map to display the
let camera = GMSCameraPosition.camera(withLatitude: 13.082680,
longitude: 80.270718,
zoom: 10.0,
bearing: 30,
viewingAngle: 40)
//Setting the googleView
googleMaps.camera = camera
googleMaps.delegate = self
googleMaps.isMyLocationEnabled = true
googleMaps.settings.myLocationButton = true
googleMaps.settings.compassButton = true
googleMaps.settings.zoomGestures = true
googleMaps.animate(to: camera)
self.view.addSubview(googleMaps)
//Setting the start and end location
let origin = "\(13.082680),\(80.270718)"
let destination = "\(15.912900),\(79.739987)"
let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"
//Rrequesting Alamofire and SwiftyJSON
Alamofire.request(url).responseJSON { response in
print(response.request as Any) // original URL request
print(response.response as Any) // HTTP URL response
print(response.data as Any) // server data
print(response.result) // result of response serialization
do {
let json = try JSON(data: response.data!)
let routes = json["routes"].arrayValue
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"].dictionary
let points = routeOverviewPolyline?["points"]?.stringValue
let path = GMSPath.init(fromEncodedPath: points!)
let polyline = GMSPolyline.init(path: path)
polyline.strokeColor = UIColor.blue
polyline.strokeWidth = 2
polyline.map = self.googleMaps
}
}
catch {
}
}
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 28.524555, longitude: 77.275111)
marker.title = "Mobiloitte"
marker.snippet = "India"
marker.map = googleMaps
//28.643091, 77.218280
let marker1 = GMSMarker()
marker1.position = CLLocationCoordinate2D(latitude: 28.643091, longitude: 77.218280)
marker1.title = "NewDelhi"
marker1.snippet = "India"
marker1.map = googleMaps
}
// MARK: function for create a marker pin on map
func createMarker(titleMarker: String, iconMarker: UIImage, latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(latitude, longitude)
marker.isDraggable=true
marker.title = titleMarker
marker.icon = iconMarker
marker.map = googleMaps
}
//MARK: - Location Manager delegates
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error to get location : \(error)")
}
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)
let locationMobi = CLLocation(latitude: 28.524555, longitude: 77.275111)
drawPath(startLocation: location!, endLocation: locationMobi)
//self.googleMaps?.animate(to: camera)
self.locationManager.stopUpdatingLocation()
}
// MARK: - GMSMapViewDelegate
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
googleMaps.isMyLocationEnabled = true
}
func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
googleMaps.isMyLocationEnabled = true
if (gesture) {
mapView.selectedMarker = nil
}
}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
googleMaps.isMyLocationEnabled = true
return false
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("COORDINATE \(coordinate)") // when you tapped coordinate
}
func didTapMyLocationButton(for mapView: GMSMapView) -> Bool {
googleMaps.isMyLocationEnabled = true
googleMaps.selectedMarker = nil
return false
}
//MARK: - Marker Delegate
func mapView(_ mapView: GMSMapView, didDrag marker: GMSMarker) {
}
func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker) {
}
func mapView(_ mapView: GMSMapView, didEndDragging marker: GMSMarker) {
self.googleMaps.reloadInputViews()
//self.polyline.map = nil;
print("marker dragged to location: \(marker.position.latitude),\(marker.position.longitude)")
let locationMobi = CLLocation(latitude: marker.position.latitude, longitude: marker.position.longitude)
self.drawPath(startLocation: locationMobi, endLocation: locationEnd)
}
//MARK: - this is function for create direction path, from start location to desination location
func drawPath(startLocation: CLLocation, endLocation: CLLocation)
{
let origin = "\(startLocation.coordinate.latitude),\(startLocation.coordinate.longitude)"
let destination = "\(endLocation.coordinate.latitude),\(endLocation.coordinate.longitude)"
self.polyline.map = nil
//self.googleMaps.clear()
let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"
Alamofire.request(url).responseJSON { response in
print(response.request as Any) // original URL request
print(response.response as Any) // HTTP URL response
print(response.data as Any) // server data
print(response.result as Any) // result of response serialization
do {
let json = try JSON(data: response.data!)
let routes = json["routes"].arrayValue
// print route using Polyline
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"].dictionary
let points = routeOverviewPolyline?["points"]?.stringValue
let path = GMSPath.init(fromEncodedPath: points!)
self.polyline = GMSPolyline.init(path: path)
self.polyline.strokeWidth = 2
self.polyline.strokeColor = UIColor.red
self.polyline.map = self.googleMaps
}
} catch {
}
}
}
// MARK: when start location tap, this will open the search location
#IBAction func openStartLocation(_ sender: UIButton) {
let autoCompleteController = GMSAutocompleteViewController()
autoCompleteController.delegate = self
// selected location
locationSelected = .startLocation
// Change text color
UISearchBar.appearance().setTextColor(color: UIColor.black)
self.locationManager.stopUpdatingLocation()
self.present(autoCompleteController, animated: true, completion: nil)
}
// MARK: when destination location tap, this will open the search location
#IBAction func openDestinationLocation(_ sender: UIButton) {
let autoCompleteController = GMSAutocompleteViewController()
autoCompleteController.delegate = self
// selected location
locationSelected = .destinationLocation
// Change text color
UISearchBar.appearance().setTextColor(color: UIColor.black)
self.locationManager.stopUpdatingLocation()
self.present(autoCompleteController, animated: true, completion: nil)
}
// MARK: SHOW DIRECTION WITH BUTTON
#IBAction func showDirection(_ sender: UIButton) {
// when button direction tapped, must call drawpath func
self.drawPath(startLocation: locationStart, endLocation: locationEnd)
}
}
// MARK: - GMS Auto Complete Delegate, for autocomplete search location
extension ViewController: GMSAutocompleteViewControllerDelegate {
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
print("Error \(error)")
}
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
// Change map location
let camera = GMSCameraPosition.camera(withLatitude: place.coordinate.latitude, longitude: place.coordinate.longitude, zoom: 16.0
)
// set coordinate to text
if locationSelected == .startLocation {
if (self.locationManager.location?.coordinate.longitude) != nil {
startLocation.text = "\(place.coordinate.latitude), \(place.coordinate.longitude)"
locationStart = CLLocation(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
createMarker(titleMarker: "Location Start", iconMarker: #imageLiteral(resourceName: "images"), latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
}else {
// handle the error by declaring default value
}
} else {
if (self.locationManager.location?.coordinate.longitude) != nil {
destinationLocation.text = "\(place.coordinate.latitude), \(place.coordinate.longitude)"
locationEnd = CLLocation(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
createMarker(titleMarker: "Location End", iconMarker: #imageLiteral(resourceName: "images"), latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
}else {
// handle the error by declaring default value
}
}
self.googleMaps.camera = camera
self.dismiss(animated: true, completion: nil)
}
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
self.dismiss(animated: true, completion: nil)
}
func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
public extension UISearchBar {
public func setTextColor(color: UIColor) {
let svs = subviews.flatMap { $0.subviews }
guard let tf = (svs.filter { $0 is UITextField }).first as? UITextField else { return }
tf.textColor = color
}
}
Here is working code to take a screenshot of ongoing video during a call in QuickBlox
#IBOutlet weak var stackView: UIStackView!
let stillImageOutput = AVCaptureStillImageOutput()
override func viewDidLoad() {
super.viewDidLoad()
QBRTCClient.initializeRTC()
QBRTCClient.instance().add(self)
cofigureVideo()
}
func cofigureVideo() {
QBRTCConfig.mediaStreamConfiguration().videoCodec = .H264
QBRTCConfig.setAnswerTimeInterval(30)
QBRTCConfig.setStatsReportTimeInterval(5)
let videoFormat = QBRTCVideoFormat.init()
videoFormat.frameRate = 30
videoFormat.pixelFormat = .format420f
videoFormat.width = 640
videoFormat.height = 480
self.videoCapture = QBRTCCameraCapture.init(videoFormat: videoFormat, position: .front)
self.videoCapture.previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.videoCapture.startSession {
self.stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
if self.videoCapture.captureSession.canAddOutput(self.stillImageOutput) {
self.videoCapture.captureSession.addOutput(self.stillImageOutput)
}
let localView = LocalVideoView.init(withPreviewLayer:self.videoCapture.previewLayer)
self.stackView.addArrangedSubview(localView)
}
}
Take photo Button Click
#IBAction func TakePhotoTapped(_ sender: Any) {
if let videoConnection = stillImageOutput.connection(with: AVMediaType.video) {
stillImageOutput.captureStillImageAsynchronously(from: videoConnection) {
(imageDataSampleBuffer, error) -> Void in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)
if let image = UIImage(data: imageData!){
// Your image is Here
}
}
}
}
When I add the annotations to the map they sometimes show and sometimes not depending on how close they are to each other. If they are in the same house lets say one won't show. How do I make both of them show? Do I need to make a custom annotation class? I heard ios11 has a clumping feature, do I need to use that? Here is the code(abridged):
import UIKit
import MapKit
import Firebase
class GameViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
fileprivate var locations = [CLLocation]()
fileprivate var userLocations = [(loc: CLLocation, name: String, team: String)]()
fileprivate var userAnnotations = [MKAnnotation]()
fileprivate var hasBeenUP = false
var ref: FIRDatabaseReference!
let uid = FIRAuth.auth()!.currentUser!.uid
var timer = Timer()
var timeLeft = 0.0
var firstTimer = Timer()
var name = ""
var team = ""
override func viewDidLoad() {
super.viewDidLoad()
let center = CLLocationCoordinate2D(latitude: 47.786769, longitude: -20.413634)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
mapView.mapType = .hybrid
locationManager.startUpdatingLocation()
ref = FIRDatabase.database().reference()
setupULSending()
getMetaInfo()
ref.child("realtimeLocations").observe(FIRDataEventType.value, with: { (snapshot) in
self.userLocations = []
for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
guard let snapshotValue = snapshot.value as? NSDictionary, let snapVal = snapshotValue[rest.key] as? NSDictionary else {
break
}
let name = snapVal["name"] as! String
let team = snapVal["team"] as? String ?? ""
if let lat = snapVal["lat"] as? Double,
let long = snapVal["long"] as? Double {
let location = CLLocation(latitude: lat, longitude: long)
self.userLocations.append((loc: location, name: name, team: team))
}else {
}
}
DispatchQueue.main.async {
self.updateUserLocation()
}
})
}
private lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.allowsBackgroundLocationUpdates = true
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
manager.requestAlwaysAuthorization()
return manager
}()
func updateUserLocation() {
for an in self.mapView.annotations {
mapView.removeAnnotation(an)
}
for loc in userLocations {
let annotation = MKPointAnnotation()
annotation.coordinate = loc.loc.coordinate
annotation.title = loc.name
annotation.subtitle = "local"
mapView.addAnnotation(annotation)
}
}
}
// MARK: - CLLocationManagerDelegate
extension GameViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations
locations: [CLLocation]) {
let location = locations.last as! CLLocation
self.locations.append(location)
}
}
On the MKAnnotationView, you have to set the MKFeatureDisplayPriority to 'required'. You can modify the annotation views by implementing MKMapViewDelegate and mapView(MKMapView, viewFor: MKAnnotation). Something like this:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
var view = mapView.dequeueReusableAnnotationView(withIdentifier: "yourIdentifier")
if view == nil {
view = MKMarkerAnnotationView(annotation: nil, reuseIdentifier: "yourIdentifier")
}
view?.displayPriority = .required
return view
}
More options for this are explained in the WWDC 2017 video 237 "What's New in MapKit"
I am working on Swift Google Maps. I cannot get the didTapMarker delegate to execute when the user taps on the marker. I put the mapView.delegate = self in the viewDidLoad method, but it did not help.
import UIKit
import GoogleMaps
import Alamofire
import ObjectMapper
import SwiftyJSON
class ViewController: UIViewController, GMSMapViewDelegate, GMUClusterManagerDelegate, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
lazy var mapView = GMSMapView()
private var clusterManager: GMUClusterManager!
//true - marker clustering / false - map markers without clustering
let isClustering : Bool = false
//true - images / false - default icons
let isCustom : Bool = false
var userLocation: CLLocation = CLLocation(latitude: 0, longitude: 0)
override func viewDidLoad() {
super.viewDidLoad()
// User Location
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 10
locationManager.startUpdatingLocation()
mapView.delegate = self
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations.last!
print("userLocation latitude \(self.userLocation.coordinate.latitude)")
print("userLocation longitude \(self.userLocation.coordinate.longitude)")
let camera = GMSCameraPosition.camera(withLatitude: userLocation.coordinate.latitude,
longitude: userLocation.coordinate.longitude, zoom: 17.0)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.settings.myLocationButton = true
mapView.settings.scrollGestures = true
mapView.settings.zoomGestures = true
mapView.isMyLocationEnabled = true
self.view = mapView
locationManager.stopUpdatingLocation()
//locationManager.delegate = nil
fetch()
}
func fetch () {
let cityLocationService = CityLocationService()
let cityService = cityLocationService.getCityService(latitude: self.userLocation.coordinate.latitude , longitude: self.userLocation.coordinate.longitude)
cityService.fetch(latitude: self.userLocation.coordinate.latitude, longitude: self.userLocation.coordinate.longitude) { (incidents) in
let incidentsJson = incidents
DispatchQueue.main.async(execute: {
self.didGetJson(incidentsJson: incidentsJson)
})
}
}
func didGetJson(incidentsJson: JSON) {
if self.isClustering {
var iconGenerator : GMUDefaultClusterIconGenerator!
if self.isCustom {
var images : [UIImage] = []
for imageID in 1...5 {
images.append(UIImage(named: "m\(imageID).png")!)
}
iconGenerator = GMUDefaultClusterIconGenerator(buckets: [ 10, 50, 100, 200, 500 ], backgroundImages: images)
} else {
iconGenerator = GMUDefaultClusterIconGenerator()
}
let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
let renderer = GMUDefaultClusterRenderer(mapView: self.mapView, clusterIconGenerator: iconGenerator)
self.clusterManager = GMUClusterManager(map: self.mapView, algorithm: algorithm, renderer: renderer)
self.addToMap(resultJson: incidentsJson, isCluster: true)
// Call cluster() after items have been added to perform the clustering and rendering on map.
self.clusterManager.cluster()
// Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events.
self.clusterManager.setDelegate(self, mapDelegate: self)
} else {
self.addToMap(resultJson: incidentsJson, isCluster: false)
}
self.view = self.mapView
}
func addToMap(resultJson: JSON, isCluster: Bool) {
for(_, subJson): (String, JSON) in resultJson {
let position = self.checkIfMutlipleCoordinates(latitude: subJson["latitude"].floatValue, longitude: subJson["longitude"].floatValue)
let id = subJson["id"]
let type = subJson["type"].stringValue
let address = subJson["address"].stringValue
// let case_number = subJson["case_number"].stringValue
let date = subJson["date"].stringValue
let markerImage = subJson["markerImage"].stringValue
if isCluster {
let item = POIItem(position: position, name: "#\(id)")
// print("pdid name=\(item.name),latitude=\(item.position.latitude),longitude=\(item.position.longitude).")
clusterManager.add(item)
} else {
let marker = GMSMarker(position: position)
marker.title = "#\(id)"
let image = UIImage(named: markerImage)
marker.icon = image?.resized(to: CGSize(width: 30, height: 30))
marker.opacity = 0.6
marker.snippet = "\r\n date: \(date) id # \(id) \r\n address: \(address) \r\n type: \(type)"
marker.map = mapView
}
}
}
func checkIfMutlipleCoordinates(latitude : Float , longitude : Float) -> CLLocationCoordinate2D{
var lat = latitude
var lng = longitude
let variation = (self.randomFloat(min: 0.0, max: 2.0) - 0.5) / 1500
lat = lat + variation
lng = lng + variation
let finalPos = CLLocationCoordinate2D(latitude: CLLocationDegrees(lat), longitude: CLLocationDegrees(lng))
return finalPos
}
func randomFloat(min: Float, max:Float) -> Float {
return (Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min
}
func clusterManager(clusterManager: GMUClusterManager, didTapCluster cluster: GMUCluster) {
let newCamera = GMSCameraPosition.camera(withTarget: cluster.position,
zoom: mapView.camera.zoom + 1)
let update = GMSCameraUpdate.setCamera(newCamera)
mapView.moveCamera(update)
}
//Show the marker title while tapping
func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
print("tapped on marker")
if marker.title == "myMarker"{
print("handle specific marker")
}
return true
}
//Optional Feature:
//Add new markers while tapping at coordinates without markers/clusters
func mapView(mapView: GMSMapView, didTapAtCoordinate coordinate: CLLocationCoordinate2D) {
let item = POIItem(position: coordinate, name: "NEW")
clusterManager.add(item)
clusterManager.cluster()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Add delegate GMSMapViewDelegate
mapView.delegate = self // in viewDidLoad
If you want to print lat and long of the touched marker, this is the code:
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
print("You tapped : \(marker.position.latitude),\(marker.position.longitude)")
return true // or false as needed.
}
And for long press, if you want to redirect to google maps.
func mapView(_ mapView: GMSMapView, didLongPressInfoWindowOf marker: GMSMarker) {
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
UIApplication.shared.open(NSURL(string:"comgooglemaps://?saddr=&daddr=\(marker.position.latitude),\(marker.position.longitude)&directionsmode=driving")! as URL, options: [:], completionHandler: nil)
}
else {
let alert = UIAlertController(title: "Google Maps not found", message: "Please install Google Maps in your device.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
This will work!!!