Move and rename iOS project so it works with KMM plugin

Enables iOS KMP debug on device in Android Studio
This commit is contained in:
Olof Hedman
2025-10-23 15:38:10 +02:00
parent ceb377d8a8
commit e8a3416658
684 changed files with 247 additions and 103 deletions

View File

@@ -0,0 +1,44 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UIWindowSceneDelegate {
private var services: Any?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey(SDKConstants.apiKey)
// Metal is the preferred renderer.
GMSServices.setMetalRendererEnabled(true)
services = GMSServices.sharedServices()
return true
}
func application(
_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions
) -> UISceneConfiguration {
let config = UISceneConfiguration(
name: "Default configuration", sessionRole: connectingSceneSession.role)
config.delegateClass = SceneDelegate.self
return config
}
}

View File

@@ -0,0 +1,29 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import CoreLocation
enum SDKConstants {
#error("Register for API Key and insert here. Then delete this line.")
static let apiKey = ""
}
extension CLLocationCoordinate2D {
static let sydney = CLLocationCoordinate2D(latitude: -33.8683, longitude: 151.2086)
// Victoria, Australia
static let victoria = CLLocationCoordinate2D(latitude: -37.81969, longitude: 144.966085)
static let newYork = CLLocationCoordinate2D(latitude: 40.761388, longitude: -73.978133)
static let mountainSceneLocation = CLLocationCoordinate2D(
latitude: -33.732022, longitude: 150.312114)
}

View File

@@ -0,0 +1,141 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class SampleListViewController: UIViewController {
static let sampleCellIdentifier = "sampleCellIdentifier"
var sampleSections = Samples.allSamples()
lazy var tableView: UITableView = UITableView()
var shouldCollapseDetailViewController = true
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
tableView.register(
UITableViewCell.self, forCellReuseIdentifier: SampleListViewController.sampleCellIdentifier)
tableView.dataSource = self
tableView.delegate = self
let searchController = UISearchController()
searchController.searchResultsUpdater = self
searchController.searchBar.autocapitalizationType = .none
searchController.searchBar.accessibilityIdentifier = "SamplesTableViewSearchBar"
searchController.obscuresBackgroundDuringPresentation = false
self.navigationItem.searchController = searchController
}
}
extension SampleListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sampleSections[section].samples.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: SampleListViewController.sampleCellIdentifier, for: indexPath)
if let sample = sample(at: indexPath) {
cell.textLabel?.text = sample.title
}
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return sampleSections.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sampleSections[section].name
}
func sample(at indexPath: IndexPath) -> Sample? {
guard indexPath.section >= 0 && indexPath.section < sampleSections.count else { return nil }
let section = sampleSections[indexPath.section]
guard indexPath.row >= 0 && indexPath.row < section.samples.count else { return nil }
return section.samples[indexPath.row]
}
}
extension SampleListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
shouldCollapseDetailViewController = false
tableView.deselectRow(at: indexPath, animated: true)
if let sample = sample(at: indexPath) {
let viewController = sample.viewControllerClass.init()
viewController.title = sample.title
let navController = UINavigationController(rootViewController: viewController)
navController.navigationBar.isTranslucent = false
showDetailViewController(navController, sender: self)
}
}
}
extension SampleListViewController: UISplitViewControllerDelegate {
func primaryViewController(forExpanding splitViewController: UISplitViewController)
-> UIViewController?
{
tableView.reloadData()
return nil
}
func primaryViewController(forCollapsing splitViewController: UISplitViewController)
-> UIViewController?
{
tableView.reloadData()
return nil
}
func splitViewController(
_ splitViewController: UISplitViewController,
collapseSecondary secondaryViewController: UIViewController,
onto primaryViewController: UIViewController
) -> Bool {
return shouldCollapseDetailViewController
}
}
extension SampleListViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
defer { tableView.reloadData() }
let text = searchController.searchBar.text
guard let filterString = text?.trimmingCharacters(in: .whitespaces).lowercased(),
!filterString.isEmpty
else {
sampleSections = Samples.allSamples()
return
}
sampleSections = Samples.allSamples().reduce(into: []) { samples, section in
guard section.samples.contains(where: { $0.matches(filterString) }) else { return }
let filteredSamples = section.samples.filter({ $0.matches(filterString) })
samples.append(Section(name: section.name, samples: filteredSamples))
}
}
}
extension Sample {
func matches(_ filter: String) -> Bool {
return title.lowercased().contains(filter)
|| String(describing: viewControllerClass).lowercased().contains(filter)
}
}

View File

@@ -0,0 +1,87 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
final class AnimatedCurrentLocationViewController: UIViewController {
private var locationMarker: GMSMarker?
private let locationManager = CLLocationManager()
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: 38.8879, longitude: -77.0200, zoom: 17)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
mapView.settings.myLocationButton = false
mapView.settings.indoorPicker = false
view = mapView
}
override func viewDidLoad() {
super.viewDidLoad()
// Setup location services
guard CLLocationManager.locationServicesEnabled() else {
print("Please enable location services")
return
}
if CLLocationManager.authorizationStatus() == .denied {
print("Please authorize location services")
return
}
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 5.0
locationManager.startUpdatingLocation()
}
}
extension AnimatedCurrentLocationViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if CLLocationManager.authorizationStatus() == .denied {
print("Please authorize location services")
return
}
print("Unable to get current location. Error: \(error.localizedDescription)")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
if let existingMaker = locationMarker {
CATransaction.begin()
CATransaction.setAnimationDuration(2.0)
existingMaker.position = location.coordinate
CATransaction.commit()
} else {
let marker = GMSMarker(position: location.coordinate)
// Animated walker images derived from a www.angryanimator.com tutorial.
// See: http://www.angryanimator.com/word/2010/11/26/tutorial-2-walk-cycle/
let animationFrames = (1...8).compactMap {
UIImage(named: "step\($0)")
}
marker.icon = UIImage.animatedImage(with: animationFrames, duration: 0.8)
// Taking into account walker's shadow.
marker.groundAnchor = CGPoint(x: 0.5, y: 0.97)
marker.map = mapView
locationMarker = marker
}
mapView.animate(with: GMSCameraUpdate.setTarget(location.coordinate, zoom: 17))
}
}

View File

@@ -0,0 +1,114 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
// Sample code for customizing the marker.
class AnimatedUIViewMarkerViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.8683, longitude: 151.2086, zoom: 5)
return GMSMapView(frame: .zero, camera: camera)
}()
private var infoView: UIImageView?
override func loadView() {
view = mapView
mapView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
mapView.clear()
addDefaultMarkers()
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self, selector: #selector(applicationWillEnterForeground),
name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc func applicationWillEnterForeground() {
mapView.clear()
addDefaultMarkers()
}
func addDefaultMarkers() {
// Add a custom 'glow' marker with a pulsing blue shadow on Sydney.
let sydneyMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -33.8683, longitude: 151.2086))
sydneyMarker.title = "Sydney!"
sydneyMarker.iconView = UIImageView(image: UIImage(named: "glow-marker"))
sydneyMarker.iconView?.contentMode = .center
sydneyMarker.map = mapView
guard let oldBounds = sydneyMarker.iconView?.bounds else { return }
sydneyMarker.iconView?.bounds = CGRect(
origin: oldBounds.origin,
size: CGSize(width: oldBounds.size.width * 2, height: oldBounds.size.height * 2))
sydneyMarker.groundAnchor = CGPoint(x: 0.5, y: 0.75)
sydneyMarker.infoWindowAnchor = CGPoint(x: 0.5, y: 0.25)
let sydneyGlow = UIImageView(image: UIImage(named: "glow-marker"))
sydneyGlow.layer.shadowColor = UIColor.blue.cgColor
sydneyGlow.layer.shadowOffset = .zero
sydneyGlow.layer.shadowRadius = 8
sydneyGlow.layer.shadowOpacity = 1.0
sydneyGlow.layer.opacity = 0.0
sydneyMarker.iconView?.addSubview(sydneyGlow)
sydneyGlow.center = CGPoint(x: oldBounds.size.width, y: oldBounds.size.height)
UIView.animate(
withDuration: 1, delay: 0, options: [.curveEaseInOut, .autoreverse, .repeat],
animations: {
sydneyGlow.layer.opacity = 1.0
},
completion: { _ in
// If the animation is ever terminated, no need to keep tracking the view for changes.
sydneyMarker.tracksViewChanges = false
})
}
}
extension AnimatedUIViewMarkerViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView? {
marker.tracksInfoWindowChanges = true
let infoView = UIImageView(image: UIImage(named: "arrow"))
infoView.backgroundColor = .clear
UIView.animate(
withDuration: 1, delay: 0, options: [.curveLinear],
animations: {
infoView.backgroundColor = UIColor(
hue: CGFloat.random(in: 0..<1), saturation: 1, brightness: 1, alpha: 1)
},
completion: { _ in
UIView.animate(
withDuration: 1, delay: 0, options: [.curveLinear],
animations: {
infoView.backgroundColor = .clear
},
completion: { _ in
marker.tracksInfoWindowChanges = false
})
})
self.infoView = infoView
return infoView
}
func mapView(_ mapView: GMSMapView, didCloseInfoWindowOf marker: GMSMarker) {
infoView = nil
marker.tracksInfoWindowChanges = false
}
}

View File

@@ -0,0 +1,55 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class BasicMapViewController: UIViewController {
var statusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Seattle coordinates
let camera = GMSCameraPosition(latitude: 47.6089945, longitude: -122.3410462, zoom: 14)
let mapView = GMSMapView(frame: view.bounds, camera: camera)
mapView.delegate = self
view = mapView
navigationController?.navigationBar.isTranslucent = false
statusLabel = UILabel(frame: .zero)
statusLabel.alpha = 0.0
statusLabel.backgroundColor = .blue
statusLabel.textColor = .white
statusLabel.textAlignment = .center
view.addSubview(statusLabel)
statusLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
statusLabel.topAnchor.constraint(equalTo: view.topAnchor),
statusLabel.heightAnchor.constraint(equalToConstant: 30),
statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
}
}
extension BasicMapViewController: GMSMapViewDelegate {
func mapViewDidStartTileRendering(_ mapView: GMSMapView) {
statusLabel.alpha = 0.8
statusLabel.text = "Rendering"
}
func mapViewDidFinishTileRendering(_ mapView: GMSMapView) {
statusLabel.alpha = 0.0
}
}

View File

@@ -0,0 +1,68 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class CameraViewController: UIViewController {
private let interval: TimeInterval = 1 / 30
private let bearing: CLLocationDirection = 10
private let angle: Double = 10
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(target: .victoria, zoom: 20, bearing: 0, viewingAngle: 0)
return GMSMapView(frame: .zero, camera: camera)
}()
private var timer: Timer?
override func loadView() {
mapView.settings.zoomGestures = false
mapView.settings.scrollGestures = false
mapView.settings.rotateGestures = false
mapView.settings.tiltGestures = false
view = mapView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Every 0.033 seconds, adjust the position of the camera.
timer = Timer.scheduledTimer(
timeInterval: interval, target: self, selector: #selector(moveCamera), userInfo: nil,
repeats: true)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
timer?.invalidate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
timer?.invalidate()
}
// Updates zoom and viewing angle, the map zoom out and the map appears in perspective, with
// far-away features appearing smaller, and nearby features appearing larger.
@objc func moveCamera() {
let zoom = max(mapView.camera.zoom - 0.1, 17.5)
let newPosition = GMSCameraPosition(
target: mapView.camera.target, zoom: zoom, bearing: mapView.camera.bearing + bearing,
viewingAngle: mapView.camera.viewingAngle + angle)
mapView.animate(to: newPosition)
}
}

View File

@@ -0,0 +1,119 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class CustomIndoorViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: 37.78318, longitude: -122.403874, zoom: 18)
let mapView = GMSMapView(frame: .zero, camera: camera)
return mapView
}()
private lazy var levelPickerView: UIPickerView = UIPickerView()
private var sampleLevels: [SampleLevel] = []
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
mapView.settings.myLocationButton = false
mapView.settings.indoorPicker = false // We are implementing a custom level picker.
mapView.isIndoorEnabled = true // Defaults to true. Set to false to hide indoor maps.
mapView.indoorDisplay.delegate = self
mapView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(mapView)
// This UIPicker will be populated with the levels of the active building.
levelPickerView.delegate = self
levelPickerView.dataSource = self
levelPickerView.showsSelectionIndicator = true
levelPickerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(levelPickerView)
let metrics: [String: Float] = ["height": 180]
let views: [String: UIView] = ["mapView": mapView, "levelPickerView": levelPickerView]
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(
withVisualFormat: "|[mapView]|", options: [], metrics: metrics, views: views)
+ NSLayoutConstraint.constraints(
withVisualFormat: "V:|[mapView][levelPickerView(height)]|", options: [], metrics: metrics,
views: views)
+ NSLayoutConstraint.constraints(
withVisualFormat: "|[levelPickerView]|", options: [], metrics: metrics, views: views))
}
}
extension CustomIndoorViewController: GMSIndoorDisplayDelegate {
func didChangeActiveBuilding(_ building: GMSIndoorBuilding?) {
guard let building = building else {
return
}
var sampleLevels: [SampleLevel] = []
if building.isUnderground {
// If this building is completely underground, add a fake 'top' floor.
sampleLevels.append(.fakeGroundLevel)
}
sampleLevels.append(contentsOf: building.levels.map({ .actualLevel($0) }))
self.sampleLevels = sampleLevels
levelPickerView.reloadAllComponents()
levelPickerView.selectRow(-1, inComponent: 0, animated: false)
}
func didChangeActiveLevel(_ level: GMSIndoorLevel?) {
// On level change, sync our level picker's selection to the IndoorDisplay.
// Since a nil level is returned for the "ground level" of an underground only building, default
// a nil value to the name of the fake ground level enum.
let sampleLevel = SampleLevel(indoorLevel: level)
if let index = sampleLevels.firstIndex(of: sampleLevel) {
let currentlySelectedIndex = levelPickerView.selectedRow(inComponent: 0)
if index != currentlySelectedIndex {
levelPickerView.selectRow(index, inComponent: 0, animated: false)
}
}
}
}
extension CustomIndoorViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// On user selection of a level in the picker, set the right level in IndoorDisplay
mapView.indoorDisplay.activeLevel = sampleLevels[row].indoorLevel
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int)
-> String?
{
return sampleLevels[row].name
}
}
extension CustomIndoorViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return sampleLevels.count
}
}

View File

@@ -0,0 +1,105 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
// Sample code for customizing the marker.
class CustomMarkersViewController: UIViewController {
private var markerCount = 0
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -37.81969, longitude: 144.966085, zoom: 4)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
view = mapView
addDefaultMarkers()
navigationController?.navigationBar.isTranslucent = false
let addButton = UIBarButtonItem(
barButtonSystemItem: .add, target: self, action: #selector(tapAdd))
addButton.accessibilityLabel = "Add Markers"
let clearButton = UIBarButtonItem(
title: "Clear Markers", style: .plain, target: self, action: #selector(tapClear))
navigationItem.rightBarButtonItems = [addButton, clearButton]
// Reset count on view load
markerCount = 0
}
func addDefaultMarkers() {
// Add a custom 'glow' marker around Sydney.
let sydneyMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -33.8683, longitude: 151.2086))
sydneyMarker.title = "Sydney!"
sydneyMarker.icon = UIImage(named: "glow-marker")
sydneyMarker.map = mapView
// Add a custom 'arrow' marker pointing to Melbourne.
let melbourneMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -37.81969, longitude: 144.966085))
melbourneMarker.title = "Melbourne!"
melbourneMarker.icon = UIImage(named: "arrow")
melbourneMarker.map = mapView
}
@objc func tapAdd() {
let bounds = GMSCoordinateBounds(region: mapView.projection.visibleRegion())
// Add a marker every 0.25 seconds for the next ten markers, randomly
// within the bounds of the camera as it is at that point.
for count in 1...10 {
DispatchQueue.main.asyncAfter(
deadline: .now() + Double(count) * 0.25,
execute: {
self.addMarker(inBounds: bounds)
})
}
}
@objc func tapClear() {
mapView.clear()
addDefaultMarkers()
// Reset count on clear
markerCount = 0
}
@objc func addMarker(inBounds bounds: GMSCoordinateBounds) {
let coordinate = bounds.randomLocation()
let marker = GMSMarker(
position: CLLocationCoordinate2D(
latitude: coordinate.latitude, longitude: coordinate.longitude))
markerCount += 1
marker.title = "Marker #\(markerCount)"
marker.appearAnimation = .pop
marker.icon = GMSMarker.markerImage(
with: UIColor(hue: CGFloat.random(in: 0..<1), saturation: 1, brightness: 1, alpha: 1))
marker.rotation = Double.random(in: -10...10)
marker.map = mapView
}
}
extension GMSCoordinateBounds {
func randomLocation() -> CLLocationCoordinate2D {
let randomLatitude = CLLocationDegrees.random(
in: southWest.latitude..<northEast.latitude)
// If the visible region crosses the antimeridian (the right-most point is
// "smaller" than the left-most point), adjust the longitude accordingly.
var maxLongitude = northEast.longitude
if maxLongitude < southWest.longitude { maxLongitude += 360 }
let randomLongitude = CLLocationDegrees.random(in: southWest.longitude..<maxLongitude)
return CLLocationCoordinate2D(
latitude: randomLatitude, longitude: randomLongitude.remainder(dividingBy: 360))
}
}

View File

@@ -0,0 +1,261 @@
// Copyright 2023 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
/// Put your Map ID in the string below. In the cloud console, configure the Map ID with a style
/// that enables the "Administrative Area Level 2" feature layer.
private let mapIDWithAdministrativeAreaLevel2Layer = ""
/// Put your Map ID in the string below. In the cloud console, configure the Map ID with a style
/// that enables the "Postal Code" feature layer.
private let mapIDWithPostalCodeLayer = ""
/// Put your Map ID in the string below. In the cloud console, configure the Map ID with a style
/// that enables the "Country" feature layer.
private let mapIDWithCountryLayer = ""
private struct FeatureLayerConfig {
let title: String
let type: FeatureType
var mapID: String
let highlightPlaceName: String
let highlightPlaceID: String
}
private class SliderControls {
let view: UIStackView
let fillColor: UISlider
let strokeColor: UISlider
let strokeWidth: UISlider
let label: UILabel
private static func addSliderAndLabel(to parent: UIStackView, text: String, initialValue: Float)
-> UISlider
{
let label = UILabel()
label.text = text
label.font = label.font.withSize(9)
parent.addArrangedSubview(label)
let slider = UISlider()
slider.value = initialValue
parent.addArrangedSubview(slider)
return slider
}
var style: FeatureStyle {
let fillColor = UIColor(
hue: CGFloat(fillColor.value),
saturation: 1,
brightness: 0.5,
alpha: 0.5
)
let strokeColor = UIColor(
hue: CGFloat(strokeColor.value),
saturation: 1,
brightness: 0.5,
alpha: 1
)
let strokeWidth = CGFloat(strokeWidth.value * 15)
return FeatureStyle(
fill: fillColor,
stroke: strokeColor,
strokeWidth: strokeWidth
)
}
var allSliders: [UISlider] {
[fillColor, strokeColor, strokeWidth]
}
init(isBaseStyle: Bool) {
view = UIStackView()
view.axis = .vertical
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white.withAlphaComponent(0.5)
fillColor = SliderControls.addSliderAndLabel(
to: view, text: "Fill color", initialValue: isBaseStyle ? 0.5 : 0.75)
strokeColor = SliderControls.addSliderAndLabel(
to: view, text: "Stroke color", initialValue: isBaseStyle ? 0 : 0.25)
strokeWidth = SliderControls.addSliderAndLabel(
to: view, text: "Stroke width", initialValue: isBaseStyle ? 0.1 : 0.2)
label = UILabel()
label.text = isBaseStyle ? "Others" : "Highlight"
label.font = label.font.withSize(10)
label.textAlignment = .center
view.addArrangedSubview(label)
}
}
class DataDrivenStylingBasicViewController: UIViewController {
private lazy var config = [
FeatureLayerConfig(
title: "Administrative Area Level 2",
type: FeatureType.administrativeAreaLevel2,
mapID: mapIDWithAdministrativeAreaLevel2Layer,
highlightPlaceName: "Nye County, NV",
highlightPlaceID: "ChIJJcLL_DeWvoARQyqHFcY2se4"
),
FeatureLayerConfig(
title: "Postal Code",
type: FeatureType.postalCode,
mapID: mapIDWithPostalCodeLayer,
highlightPlaceName: "89049",
highlightPlaceID: "ChIJCY_aZdEwuoARZDbZn-snj68"
),
FeatureLayerConfig(
title: "Country",
type: FeatureType.country,
mapID: mapIDWithCountryLayer,
highlightPlaceName: "Senegal",
highlightPlaceID: "ChIJcbvFs_VywQ4RQFlhmVClRlo"
),
]
private lazy var segmentedControl = UISegmentedControl(items: config.map { $0.title })
private lazy var toggle = UISwitch()
private lazy var highlightStyleSliderControls = SliderControls(isBaseStyle: false)
private lazy var baseStyleSliderControls = SliderControls(isBaseStyle: true)
private var activeConfig: FeatureLayerConfig? {
guard segmentedControl.selectedSegmentIndex != UISegmentedControl.noSegment else { return nil }
return config[segmentedControl.selectedSegmentIndex]
}
private var mainView: UIView? {
get {
view.subviews.first
}
set {
view.subviews.first?.removeFromSuperview()
let newView = newValue ?? UIView()
view.insertSubview(newView, at: 0)
newView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(
[
newView.topAnchor.constraint(equalTo: view.topAnchor),
newView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
newView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
newView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
}
private lazy var featureTypeSelectionLabel: UILabel = {
let label = UILabel()
label.text = "Select a feature type"
label.textAlignment = .center
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
mainView = featureTypeSelectionLabel
segmentedControl.addTarget(
self, action: #selector(changeMapType), for: .valueChanged)
navigationItem.titleView = segmentedControl
toggle.addTarget(self, action: #selector(activateFeatureLayer), for: .valueChanged)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: toggle)
(highlightStyleSliderControls.allSliders + baseStyleSliderControls.allSliders).forEach {
$0.addTarget(self, action: #selector(activateFeatureLayer), for: .valueChanged)
}
view.addSubview(highlightStyleSliderControls.view)
view.addSubview(baseStyleSliderControls.view)
NSLayoutConstraint.activate(
[
highlightStyleSliderControls.view.widthAnchor.constraint(
equalTo: baseStyleSliderControls.view.widthAnchor),
highlightStyleSliderControls.view.trailingAnchor.constraint(
equalTo: baseStyleSliderControls.view.leadingAnchor),
highlightStyleSliderControls.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
baseStyleSliderControls.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
highlightStyleSliderControls.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
baseStyleSliderControls.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
changeMapType()
}
@objc func changeMapType() {
guard let activeConfig else {
mainView = featureTypeSelectionLabel
highlightStyleSliderControls.view.isHidden = true
baseStyleSliderControls.view.isHidden = true
return
}
let configIndex = segmentedControl.selectedSegmentIndex
var mapID = activeConfig.mapID
if mapID.isEmpty {
promptForMapID(description: "with \(activeConfig.title) layer enabled") {
self.config[configIndex].mapID = $0
self.setUp()
}
} else {
self.setUp()
}
}
private func setUp() {
guard let activeConfig else {
return
}
guard !activeConfig.mapID.isEmpty else {
let label = UILabel()
label.text = "A Map ID is required"
label.textAlignment = .center
mainView = label
segmentedControl.selectedSegmentIndex = UISegmentedControl.noSegment
highlightStyleSliderControls.view.isHidden = true
baseStyleSliderControls.view.isHidden = true
return
}
let camera = GMSCameraPosition(latitude: 38.590240, longitude: -95.712891, zoom: 4)
mainView = GMSMapView(
frame: .zero, mapID: GMSMapID(identifier: activeConfig.mapID), camera: camera)
toggle.setOn(false, animated: false)
highlightStyleSliderControls.label.text = activeConfig.highlightPlaceName
highlightStyleSliderControls.view.isHidden = false
baseStyleSliderControls.view.isHidden = false
}
@objc func activateFeatureLayer() {
guard let activeConfig, let mapView = mainView as? GMSMapView else { return }
let layer = mapView.featureLayer(of: activeConfig.type)
if toggle.isOn {
if !layer.isAvailable {
showToast(
message: "Feature layer \(activeConfig.title) is not available; see debug log for details"
)
}
let placeID = activeConfig.highlightPlaceID
let specialStyle = highlightStyleSliderControls.style
let style = baseStyleSliderControls.style
layer.style = { ($0.placeID == placeID) ? specialStyle : style }
} else {
layer.style = nil
}
}
}

View File

@@ -0,0 +1,242 @@
// Copyright 2022 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
/// Put your Map ID in the string below. In the cloud console, configure the Map ID with a style
/// that enables all data-driven styling feature layers.
private let mapIDWithMultipleLayers = ""
class DataDrivenStylingEventsViewController: UIViewController {
private let sectionIdentifierForLayerToggles = "sectionIdentifierForLayerToggles"
private let cellIdentifier = "cellIdentifier"
private lazy var featureLayerStates: [FeatureType: FeatureLayerState] = [
.country: FeatureLayerState(label: "Country", color: .purple),
.administrativeAreaLevel1: FeatureLayerState(label: "Admin1", color: .orange),
.administrativeAreaLevel2: FeatureLayerState(label: "Admin2", color: .blue),
.locality: FeatureLayerState(label: "Locality", color: .red),
.postalCode: FeatureLayerState(label: "Postal Code", color: .brown),
.schoolDistrict: FeatureLayerState(label: "School District", color: .cyan),
]
private lazy var tableView = {
let view = UITableView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundView = nil
view.backgroundColor = .white.withAlphaComponent(0.75)
view.contentInsetAdjustmentBehavior = .never
view.contentInset = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: -10)
view.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
return view
}()
private lazy var dataSource = UITableViewDiffableDataSource<String, String>(tableView: tableView)
{
(tableView: UITableView, indexPath: IndexPath, itemIdentifier: String) -> UITableViewCell? in
guard let section = self.sectionIdentifier(for: indexPath) else { return nil }
let isToggleControl = section == self.sectionIdentifierForLayerToggles
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath)
let textLabel = cell.textLabel!
if isToggleControl {
if let featureLayerState = self.featureLayerStates[FeatureType(rawValue: itemIdentifier)] {
let layerActive = featureLayerState.layer != nil
textLabel.text = "\(layerActive ? "☑" : "☐") \(featureLayerState.label)"
textLabel.font = textLabel.font.withSize(14)
textLabel.textColor = featureLayerState.color.withAlphaComponent(
layerActive ? 1 : 0.75)
}
} else {
if let featureLayerState = self.featureLayerStates[FeatureType(rawValue: section)] {
textLabel.text = featureLayerState.featureNameByPlaceID[itemIdentifier]
textLabel.font = textLabel.font.withSize(12)
textLabel.textColor = featureLayerState.color
}
}
return cell
}
private var mapID = mapIDWithMultipleLayers
private lazy var mapView = {
let camera = GMSCameraPosition(latitude: 47.61, longitude: -122.34, zoom: 10)
let view = GMSMapView(
frame: .zero, mapID: GMSMapID(identifier: mapID), camera: camera)
view.delegate = self
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
if mapID.isEmpty {
promptForMapID(description: "with all data-driven styling layers enabled") {
self.mapID = $0
self.setUp()
}
} else {
setUp()
}
}
private func setUp() {
guard mapID.count != 0 else {
let label = UILabel()
label.text = "A Map ID is required"
label.textAlignment = .center
view = label
return
}
view = mapView
tableView.dataSource = dataSource
tableView.delegate = self
mapView.addSubview(tableView)
NSLayoutConstraint.activate(
[
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.widthAnchor.constraint(equalToConstant: 120),
])
let featureTypes: Array = featureLayerStates.keys.map({ $0.rawValue }).sorted()
var diff = NSDiffableDataSourceSnapshot<String, String>()
diff.appendSections([sectionIdentifierForLayerToggles])
diff.appendSections(featureTypes)
diff.appendItems(
featureTypes,
toSection: sectionIdentifierForLayerToggles
)
dataSource.apply(diff)
}
}
extension DataDrivenStylingEventsViewController: GMSMapViewDelegate {
func mapView(
_ mapView: GMSMapView, didTap features: [Feature],
in featureLayer: FeatureLayer<Feature>, atLocation: CLLocationCoordinate2D
) {
let featureType = featureLayer.featureType
guard let state = featureLayerStates[featureType] else { return }
var snapshot = dataSource.snapshot()
for case let feature as PlaceFeature in features {
if state.togglePlaceSelection(feature.placeID) {
snapshot.appendItems([feature.placeID], toSection: featureType.rawValue)
} else {
snapshot.deleteItems([feature.placeID])
}
}
dataSource.apply(snapshot)
(featureLayer as? FeatureLayer<PlaceFeature>)?.style = state.makeStyleBlock()
}
}
extension DataDrivenStylingEventsViewController: UITableViewDelegate {
fileprivate func sectionIdentifier(for indexPath: IndexPath) -> String? {
if #available(iOS 15.0, *) {
return dataSource.sectionIdentifier(for: indexPath.section)
} else {
return dataSource.snapshot().sectionIdentifiers[indexPath.section]
}
}
func tableView(
_ tableView: UITableView,
heightForRowAt indexPath: IndexPath
) -> CGFloat {
return (sectionIdentifier(for: indexPath) == sectionIdentifierForLayerToggles)
? 36 : 24
}
func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {
guard let section = sectionIdentifier(for: indexPath),
let itemIdentifier = dataSource.itemIdentifier(for: indexPath)
else { return }
if section == sectionIdentifierForLayerToggles {
let featureType = FeatureType(rawValue: itemIdentifier)
guard let state = featureLayerStates[featureType] else { return }
if let layer = state.layer {
layer.style = nil
state.layer = nil
} else {
let layer = mapView.featureLayer(of: featureType)
layer.style = state.makeStyleBlock()
state.layer = layer
if !layer.isAvailable {
showToast(
message:
"Feature layer \(state.label) is not available; see debug log for details"
)
}
}
var diff = dataSource.snapshot()
diff.reloadItems([itemIdentifier])
dataSource.apply(diff)
} else {
guard let state = featureLayerStates[FeatureType(rawValue: section)] else { return }
let previouslySelected = !state.togglePlaceSelection(itemIdentifier)
assert(previouslySelected)
state.layer?.style = state.makeStyleBlock()
var diff = dataSource.snapshot()
diff.deleteItems([itemIdentifier])
dataSource.apply(diff)
}
}
}
private class FeatureLayerState {
let label: String
let color: UIColor
var layer: FeatureLayer<PlaceFeature>? = nil
private(set) var featureNameByPlaceID: [String: String] = [:]
init(label: String, color: UIColor) {
self.label = label
self.color = color
}
// Toggles selection state of a place ID, returns true if it's added, false if it's removed.
func togglePlaceSelection(_ placeID: String) -> Bool {
let adding = featureNameByPlaceID.removeValue(forKey: placeID) == nil
if adding {
featureNameByPlaceID[placeID] = "[Place \(placeID)]"
}
return adding
}
func updateFeatureName(for placeID: String, to name: String?) {
// Don't add the place to featureNameByPlaceID if it isn't already selected.
if featureNameByPlaceID[placeID] == nil { return }
featureNameByPlaceID[placeID] = name ?? "[Error \(placeID)]"
}
func makeStyleBlock() -> ((PlaceFeature) -> FeatureStyle) {
let nonSelectedStyle = FeatureStyle(
fill: color.withAlphaComponent(0.25),
stroke: color,
strokeWidth: 1.5
)
let selectedStyle = FeatureStyle(
fill: color.withAlphaComponent(0.5),
stroke: color,
strokeWidth: 3
)
return { (self.featureNameByPlaceID[$0.placeID] != nil) ? selectedStyle : nonSelectedStyle }
}
}

View File

@@ -0,0 +1,375 @@
// Copyright 2022 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
/// Put your Map ID in the string below. In the cloud console, configure the Map ID with a style
/// that enables the "Administrative Area Level 2" feature layer.
private let mapIDWithAdministrativeAreaLevel2Layer = ""
private let initialSearches = [
"Nye County", "San Bernardino County", "Juab County", "Crook County",
]
private func buildSearchRequest(forPlaceName placeName: String) -> URLRequest {
// URL initializer only returns nil when the URL string is malformed, but it is a known valid
// string literal here.
let requestURL = URL(string: "https://places.googleapis.com/v1/places:searchText")!
var urlRequest = URLRequest(url: requestURL)
urlRequest.httpMethod = "POST"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue(SDKConstants.apiKey, forHTTPHeaderField: "X-Goog-Api-Key")
urlRequest.addValue("places.id", forHTTPHeaderField: "X-Goog-FieldMask")
urlRequest.addValue(
Bundle.main.bundleIdentifier ?? "unknown_ios", forHTTPHeaderField: "X-Ios-Bundle-Identifier")
urlRequest.httpBody = try! JSONSerialization.data(
withJSONObject: [
"textQuery": placeName,
"includedType": "administrative_area_level_2",
"languageCode": "en",
], options: [])
return urlRequest
}
private struct PlaceTextSearchResponse: Codable {
struct Place: Codable {
let id: String
}
let places: [Place]
}
private class PlaceLookupController: NSObject {
let serial: Int
let controller: DataDrivenStylingSearchViewController
var name: String? {
didSet {
let effectiveName = name ?? ""
view.text = effectiveName
guard !effectiveName.isEmpty else { return }
let task = controller.urlSession.dataTask(
with: buildSearchRequest(forPlaceName: effectiveName)
) {
data, response, error in
if let error {
self.textSearchFailed(with: error)
return
}
do {
guard let data else {
preconditionFailure("Response \(response) is empty")
}
let decoder = JSONDecoder()
let decodedResponse = try decoder.decode(PlaceTextSearchResponse.self, from: data)
if let extractedID = decodedResponse.places.first?.id {
self.placeID = extractedID
} else {
preconditionFailure("Place ID not found from \(response)")
}
} catch {
self.textSearchFailed(with: error)
}
}
task.resume()
}
}
var color: UIColor = .clear {
didSet {
colorSelectionButton.setTitleColor(color, for: .normal)
controller.reloadStyle()
}
}
private(set) var placeID: String? {
didSet {
colorSelectionButton.setTitle("⬤", for: .normal)
controller.reloadStyle()
}
}
private lazy var colorSelectionButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = button.titleLabel?.font.withSize(12)
button.setTitle("❓", for: .normal)
button.addTarget(self, action: #selector(selectionButtonTapped), for: .touchUpInside)
return button
}()
lazy var view: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.backgroundColor = .white.withAlphaComponent(0.5)
textField.font = textField.font?.withSize(12)
textField.delegate = self
textField.leftView = colorSelectionButton
textField.leftViewMode = .always
let clearButton = UIButton()
clearButton.titleLabel?.font = clearButton.titleLabel?.font.withSize(12)
clearButton.setTitle("🗑️", for: .normal)
clearButton.addTarget(self, action: #selector(remove), for: .touchUpInside)
textField.rightView = clearButton
textField.rightViewMode = .unlessEditing
textField.clearButtonMode = .whileEditing
return textField
}()
init(controller: DataDrivenStylingSearchViewController, serial: Int) {
self.controller = controller
self.serial = serial
}
func focusTextEdit() {
view.becomeFirstResponder()
}
@objc func remove() {
controller.removeFeature(self)
}
private func textSearchFailed(with error: Error) {
colorSelectionButton.setTitle("❗", for: .normal)
NSLog("Feature \(name) not found: \(error)")
}
@objc func selectionButtonTapped() {
let selector = UIColorPickerViewController()
selector.selectedColor = color ?? .white
selector.supportsAlpha = false
selector.delegate = self
controller.present(selector, animated: true)
}
}
extension PlaceLookupController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
let text = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !text.isEmpty else {
colorSelectionButton.setTitle("❓", for: .normal)
return
}
guard name != text else { return }
colorSelectionButton.setTitle("⏳", for: .normal)
name = text
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
}
extension PlaceLookupController: UIColorPickerViewControllerDelegate {
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
color = viewController.selectedColor
}
}
/// Table view that does not intercept gestures outside table cells.
class NotCapturingTouchesTableView: UITableView {
// This override causes the view to not intercept gestures, unless the gesture occurs on one of
// this view's subviews. The UITableView should not prevent the map from panning/zooming/tilting.
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
// If no descendent of this view contains the specified point, return nil. nil is returned if
// the point does not fit inside the view.
if view == self {
return nil
} else {
// If there is a descendent of this view that contains the specified point, return that view.
return view
}
}
}
class DataDrivenStylingSearchViewController: UIViewController {
private let cellIdentifier = "cellIdentifier"
fileprivate let urlSession = URLSession(
configuration: .default, delegate: nil,
delegateQueue: .main)
private var placeSerial = 0
private var places: [Int: PlaceLookupController] = [:]
private var computedColorMapping: [String: UIColor]?
private lazy var tableView: UITableView = {
let view = NotCapturingTouchesTableView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundView = nil
view.backgroundColor = .clear
view.contentInsetAdjustmentBehavior = .never
view.rowHeight = 28
view.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
return view
}()
private lazy var dataSource = UITableViewDiffableDataSource<Int, Int>(tableView: tableView) {
(tableView: UITableView, indexPath: IndexPath, itemIdentifier: Int) -> UITableViewCell? in
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath)
cell.contentView.subviews.forEach { $0.removeFromSuperview() }
cell.backgroundColor = .clear
guard let view = self.places[itemIdentifier]?.view else { return cell }
cell.contentView.addSubview(view)
NSLayoutConstraint.activate(
[
cell.contentView.topAnchor.constraint(equalTo: view.topAnchor),
cell.contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
cell.contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
cell.contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
return cell
}
private var mapID = mapIDWithAdministrativeAreaLevel2Layer
private lazy var mapView = {
let camera = GMSCameraPosition(latitude: 40, longitude: -117.5, zoom: 5.5)
let view = GMSMapView(
frame: .zero, mapID: GMSMapID(identifier: mapID), camera: camera)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
if mapID.isEmpty {
promptForMapID(description: "with all data-driven styling layers enabled") {
self.mapID = $0
self.setUp()
}
} else {
setUp()
}
}
private func setUp() {
guard mapID.count != 0 else {
let label = UILabel()
label.text = "A Map ID is required"
label.textAlignment = .center
view = label
return
}
tableView.dataSource = dataSource
view.addSubview(mapView)
view.addSubview(tableView)
NSLayoutConstraint.activate(
[
mapView.topAnchor.constraint(equalTo: view.topAnchor),
mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
])
let addAction = UIAction(
title: "+"
) { _ in self.addButtonTapped() }
navigationItem.rightBarButtonItem = UIBarButtonItem(primaryAction: addAction)
var diff = NSDiffableDataSourceSnapshot<Int, Int>()
diff.appendSections([0])
diff.appendItems(
initialSearches.map { addFeature(name: $0).0 }
)
dataSource.apply(diff)
}
private func addButtonTapped() {
let (itemIdentifier, lookup) = addFeature()
var diff = dataSource.snapshot()
diff.appendItems([itemIdentifier])
dataSource.apply(diff)
DispatchQueue.main.async {
lookup.focusTextEdit()
}
}
private func nextColorHue() -> Float {
var hueValues: [Float] = places.compactMap { (_, config) in
var hue = CGFloat.nan
if config.color.getHue(&hue, saturation: nil, brightness: nil, alpha: nil) {
if hue >= 0 && hue <= 1 {
return Float(hue)
}
}
return nil
}
var candidateHue = (hueValues.first ?? 0) - 0.5
if hueValues.count > 1 {
hueValues.sort()
let diffs =
[1 + hueValues.first! - hueValues.last!] + zip(hueValues.dropFirst(), hueValues).map(-)
let (largestGap, endOfLargestGap) = (zip(diffs, hueValues).max { $0.0 < $1.0 })!
candidateHue = endOfLargestGap - largestGap / 2
}
if candidateHue < 0 {
candidateHue += 1
}
return candidateHue
}
private func addFeature(name: String? = nil) -> (Int, PlaceLookupController) {
placeSerial += 1
let itemIdentifier = placeSerial
let featureConfig = PlaceLookupController(controller: self, serial: itemIdentifier)
featureConfig.color = UIColor(
hue: CGFloat(nextColorHue()),
saturation: 1,
brightness: 0.75,
alpha: 1)
featureConfig.name = name
places[itemIdentifier] = featureConfig
return (itemIdentifier, featureConfig)
}
fileprivate func removeFeature(_ feature: PlaceLookupController) {
guard places.count > 1 else { return }
var diff = dataSource.snapshot()
diff.deleteItems([feature.serial])
dataSource.apply(diff)
places.removeValue(forKey: feature.serial)
reloadStyle()
}
fileprivate func reloadStyle() {
var colorMapping: [String: UIColor] = Dictionary(
places.compactMap { (_, config) in
config.placeID.map { ($0, config.color) }
},
uniquingKeysWith: { (first, _) in first })
// Skip restyling if the mapping hasn't actually changed, since restyling can be expensive.
guard colorMapping != computedColorMapping else { return }
computedColorMapping = colorMapping
mapView.featureLayer(of: .administrativeAreaLevel2).style = {
guard let color = colorMapping[$0.placeID] else { return nil }
return FeatureStyle(
fill: color.withAlphaComponent(0.5),
stroke: color,
strokeWidth: 1.5
)
}
}
}

View File

@@ -0,0 +1,64 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class DoubleMapViewController: UIViewController {
private lazy var sanFranciscoCamera = GMSCameraPosition(
latitude: 37.7847, longitude: -122.41, zoom: 5)
private lazy var mapView: GMSMapView = {
let mapView = GMSMapView(frame: .zero, camera: sanFranciscoCamera)
return mapView
}()
private lazy var boundMapView: GMSMapView = {
let mapView = GMSMapView(frame: .zero, camera: sanFranciscoCamera)
return mapView
}()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(mapView)
boundMapView.settings.scrollGestures = false
boundMapView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(boundMapView)
NSLayoutConstraint.activate([
mapView.leftAnchor.constraint(equalTo: view.leftAnchor),
mapView.rightAnchor.constraint(equalTo: view.rightAnchor),
boundMapView.leftAnchor.constraint(equalTo: view.leftAnchor),
boundMapView.rightAnchor.constraint(equalTo: view.rightAnchor),
mapView.topAnchor.constraint(equalTo: view.topAnchor),
boundMapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
mapView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
boundMapView.topAnchor.constraint(equalTo: mapView.bottomAnchor),
])
}
}
extension DoubleMapViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
let previousCamera = boundMapView.camera
boundMapView.camera = GMSCameraPosition(
target: position.target, zoom: previousCamera.zoom, bearing: previousCamera.bearing,
viewingAngle: previousCamera.viewingAngle)
}
}

View File

@@ -0,0 +1,78 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class FitBoundsViewController: UIViewController {
private let markerImageName = "glow-marker"
private let anotherSydneyLocation = CLLocationCoordinate2D(
latitude: -33.8683, longitude: 149.2086)
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(target: .victoria, zoom: 4)
return GMSMapView(frame: .zero, camera: camera)
}()
// Creates a list of markers, adding the Sydney marker.
private lazy var markers: [GMSMarker] = {
// Adds default markers around Sydney.
let sydneyMarker = GMSMarker(position: .sydney)
sydneyMarker.title = "Sydney!"
sydneyMarker.icon = UIImage(named: markerImageName)
let anotherSydneyMarker = GMSMarker()
anotherSydneyMarker.title = "Sydney 2!"
anotherSydneyMarker.icon = UIImage(named: markerImageName)
anotherSydneyMarker.position = anotherSydneyLocation
return [sydneyMarker, anotherSydneyMarker]
}()
override func loadView() {
mapView.delegate = self
view = mapView
// Creates a button that, when pressed, updates the camera to fit the bounds.
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Fit Bounds", style: .plain, target: self, action: #selector(fitBounds))
}
override func viewDidLoad() {
super.viewDidLoad()
markers.forEach { marker in
marker.map = mapView
}
}
@objc func fitBounds() {
var bounds = GMSCoordinateBounds()
for marker in markers {
bounds = bounds.includingCoordinate(marker.position)
}
guard bounds.isValid else { return }
mapView.moveCamera(GMSCameraUpdate.fit(bounds, withPadding: 50))
}
}
extension FitBoundsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
let marker = GMSMarker(position: coordinate)
marker.title = "Marker at: \(coordinate.latitude), \(coordinate.longitude)"
marker.appearAnimation = .pop
marker.map = mapView
markers.append(marker)
}
}

View File

@@ -0,0 +1,27 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class FixedPanoramaViewController: UIViewController {
override func loadView() {
let panoramaView = GMSPanoramaView(frame: .zero)
panoramaView.moveNearCoordinate(.mountainSceneLocation)
panoramaView.camera = GMSPanoramaCamera(heading: 180, pitch: -10, zoom: 0)
panoramaView.orientationGestures = false
panoramaView.navigationGestures = false
panoramaView.navigationLinksHidden = true
view = panoramaView
}
}

View File

@@ -0,0 +1,87 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class FrameRateViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 6)
return GMSMapView(frame: .zero, camera: camera)
}()
private lazy var statusTextView: UITextView = UITextView()
override func loadView() {
view = mapView
statusTextView.text = ""
statusTextView.textAlignment = .center
statusTextView.backgroundColor = UIColor(white: 1, alpha: 0.8)
statusTextView.isEditable = false
view.addSubview(statusTextView)
statusTextView.sizeToFit()
// Add a button toggling through modes.
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .play, target: self, action: #selector(changeFrameRate))
updateStatus()
statusTextView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
statusTextView.leftAnchor.constraint(equalTo: view.leftAnchor),
statusTextView.rightAnchor.constraint(equalTo: view.rightAnchor),
statusTextView.heightAnchor.constraint(greaterThanOrEqualToConstant: 24),
])
NSLayoutConstraint.activate([
statusTextView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
])
}
@objc func changeFrameRate() {
mapView.preferredFrameRate = nextFrameRate()
updateStatus()
}
func nextFrameRate() -> GMSFrameRate {
switch mapView.preferredFrameRate {
case .powerSave:
return .conservative
case .conservative:
return .maximum
default:
return .powerSave
}
}
func updateStatus() {
statusTextView.text = "Preferred frame rate: \(mapView.preferredFrameRate.name)"
}
}
extension GMSFrameRate {
var name: String {
switch self {
case .powerSave:
return "PowerSave"
case .conservative:
return "Conservative"
default:
return "Maximum"
}
}
}

View File

@@ -0,0 +1,23 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
extension GMSMapStyle {
convenience init?(named fileName: String) throws {
guard let styleURL = Bundle.main.url(forResource: fileName, withExtension: "json") else {
return nil
}
try self.init(contentsOfFileURL: styleURL)
}
}

View File

@@ -0,0 +1,56 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
// Sample code for GeoCoder service.
class GeocoderViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12)
return GMSMapView(frame: .zero, camera: camera)
}()
private lazy var geocoder = GMSGeocoder()
override func loadView() {
view = mapView
mapView.delegate = self
}
}
extension GeocoderViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
// On a long press, reverse geocode this location.
geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
guard let address = response?.firstResult() else {
let errorMessage = error.map { String(describing: $0) } ?? "<no error>"
print(
"Could not reverse geocode point (\(coordinate.latitude), \(coordinate.longitude)): \(errorMessage)"
)
return
}
print("Geocoder result: \(address)")
let marker = GMSMarker(position: address.coordinate)
marker.appearAnimation = .pop
marker.map = mapView
guard let lines = address.lines, let title = lines.first else { return }
marker.title = title
if lines.count > 1 {
marker.snippet = lines[1]
}
}
}
}

View File

@@ -0,0 +1,72 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class GestureControlViewController: UIViewController {
private let holderHeight: CGFloat = 60
private let zoomLabelInset: CGFloat = 16
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -25.5605, longitude: 133.605097, zoom: 3)
return GMSMapView(frame: .zero, camera: camera)
}()
private lazy var zoomSwitch: UISwitch = UISwitch(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(mapView)
let holder = UIView(frame: .zero)
holder.backgroundColor = UIColor(white: 1, alpha: 0.8)
view.addSubview(holder)
let zoomLabel = UILabel(frame: .zero)
zoomLabel.text = "Zoom gestures"
zoomLabel.font = .boldSystemFont(ofSize: 18)
holder.addSubview(zoomLabel)
// Control zooming.
holder.addSubview(zoomSwitch)
zoomSwitch.addTarget(self, action: #selector(toggleZoom), for: .valueChanged)
zoomSwitch.isOn = true
[mapView, holder, zoomLabel, zoomSwitch].forEach({
$0.translatesAutoresizingMaskIntoConstraints = false
})
NSLayoutConstraint.activate([
mapView.leftAnchor.constraint(equalTo: view.leftAnchor),
mapView.rightAnchor.constraint(equalTo: view.rightAnchor),
mapView.topAnchor.constraint(equalTo: view.topAnchor),
mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
holder.heightAnchor.constraint(equalToConstant: holderHeight),
holder.centerXAnchor.constraint(equalTo: view.centerXAnchor),
holder.widthAnchor.constraint(equalTo: view.widthAnchor),
zoomLabel.leftAnchor.constraint(equalTo: holder.leftAnchor, constant: zoomLabelInset),
zoomLabel.centerYAnchor.constraint(equalTo: holder.centerYAnchor),
zoomSwitch.rightAnchor.constraint(equalTo: holder.rightAnchor, constant: -zoomLabelInset),
zoomSwitch.centerYAnchor.constraint(
equalTo: holder.centerYAnchor),
])
NSLayoutConstraint.activate([
holder.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
])
}
@objc func toggleZoom() {
mapView.settings.zoomGestures = zoomSwitch.isOn
}
}

View File

@@ -0,0 +1,79 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
struct Coordinate: Decodable {
let latitude: Double
let longitude: Double
let elevation: Double
enum CodingKeys: String, CodingKey {
case elevation
case latitude = "lat"
case longitude = "lng"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
latitude = try container.decode(Double.self, forKey: .latitude)
longitude = try container.decode(Double.self, forKey: .longitude)
elevation = try container.decode(Double.self, forKey: .elevation)
}
}
final class GradientPolylinesViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(
latitude: 44.1314, longitude: 9.6921, zoom: 14.059, bearing: 328, viewingAngle: 40)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
view = mapView
}
override func viewDidLoad() {
super.viewDidLoad()
addTrackToMap()
}
private func addTrackToMap() {
guard let filePath = Bundle.main.path(forResource: "track", ofType: "json") else { return }
guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else { return }
guard let track = try? JSONDecoder().decode([Coordinate].self, from: data)
else {
return
}
let path = GMSMutablePath()
var colorSpans: [GMSStyleSpan] = []
var previousColor: UIColor?
for coordinate in track {
path.addLatitude(coordinate.latitude, longitude: coordinate.longitude)
let elevation = CGFloat(coordinate.elevation)
let toColor = UIColor(hue: elevation / 700.0, saturation: 1, brightness: 0.9, alpha: 1)
let fromColor = previousColor ?? toColor
let style = GMSStrokeStyle.gradient(from: fromColor, to: toColor)
colorSpans.append(GMSStyleSpan(style: style))
previousColor = toColor
}
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 6
polyline.map = mapView
polyline.spans = colorSpans
}
}

View File

@@ -0,0 +1,46 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
final class GroundOverlayViewController: UIViewController {
override func loadView() {
let southWest = CLLocationCoordinate2D(latitude: 40.712216, longitude: -74.22655)
let northEast = CLLocationCoordinate2D(latitude: 40.773941, longitude: -74.12544)
let overlayBounds = GMSCoordinateBounds(coordinate: southWest, coordinate: northEast)
// Choose the midpoint of the coordinate to focus the camera on.
let newark = GMSGeometryInterpolate(southWest, northEast, 0.5)
let cameraPosition = GMSCameraPosition(target: newark, zoom: 12, bearing: 0, viewingAngle: 45)
let mapView = GMSMapView(frame: .zero, camera: cameraPosition)
mapView.delegate = self
view = mapView
// Add the ground overlay, centered in Newark, NJ
let groundOverlay = GMSGroundOverlay()
// Image from http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg
groundOverlay.icon = UIImage(named: "newark_nj_1922.jpg")
groundOverlay.isTappable = true
groundOverlay.position = newark
groundOverlay.bounds = overlayBounds
groundOverlay.map = mapView
}
}
extension GroundOverlayViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {
guard let groundOverlay = overlay as? GMSGroundOverlay else { return }
groundOverlay.opacity = Float.random(in: 0.5..<1)
}
}

View File

@@ -0,0 +1,143 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
struct Exhibit: Decodable {
let key: String
let name: String
let latitude: Double
let longitude: Double
let level: String
private enum CodingKeys: String, CodingKey {
case key, name
case latitude = "lat"
case longitude = "lng"
case level
}
var position: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
class IndoorMuseumNavigationViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: 38.8879, longitude: -77.0200, zoom: 17)
let mapView = GMSMapView(frame: .zero, camera: camera)
mapView.settings.myLocationButton = false
mapView.settings.indoorPicker = false
return mapView
}()
private lazy var segmentedControl = UISegmentedControl()
private var exhibits: [Exhibit]?
private var selectedExhibit: Exhibit?
private var selectedExhibitMarker: GMSMarker?
private var sampleLevels: [SampleLevel] = []
override func loadView() {
view = mapView
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.indoorDisplay.delegate = self
segmentedControl.tintColor = UIColor(red: 0.373, green: 0.667, blue: 0.882, alpha: 1.0)
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.addTarget(
self, action: #selector(changeExhibit), for: .valueChanged)
view.addSubview(segmentedControl)
NSLayoutConstraint.activate([
segmentedControl.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
segmentedControl.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor),
])
// Load the exhibits configuration from JSON
if let jsonPath = Bundle.main.path(forResource: "museum-exhibits", ofType: "json") {
if let data = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) {
exhibits = try? JSONDecoder().decode([Exhibit].self, from: data)
}
}
if let exhibits = exhibits {
for (i, exhibit) in exhibits.enumerated() {
segmentedControl.insertSegment(
with: UIImage(named: exhibit.key), at: i, animated: false)
}
}
}
func moveMarker() {
guard let selectedExhibit = selectedExhibit else {
return
}
if let selectedExhibitMarker = selectedExhibitMarker {
selectedExhibitMarker.position = selectedExhibit.position
} else {
selectedExhibitMarker = GMSMarker(position: selectedExhibit.position)
selectedExhibitMarker?.map = mapView
}
selectedExhibitMarker?.title = selectedExhibit.name
mapView.animate(toLocation: selectedExhibit.position)
mapView.animate(toZoom: 19)
}
@objc func changeExhibit() {
guard let exhibits = exhibits else {
return
}
selectedExhibit = exhibits[segmentedControl.selectedSegmentIndex]
moveMarker()
}
}
extension IndoorMuseumNavigationViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
guard let selectedExhibit = selectedExhibit,
let selectedSampleLevel = sampleLevels.first(where: { $0.shortName == selectedExhibit.level }
),
let activeLevel = selectedSampleLevel.indoorLevel
else {
return
}
if mapView.projection.contains(selectedExhibit.position) {
mapView.indoorDisplay.activeLevel = activeLevel
}
}
}
extension IndoorMuseumNavigationViewController: GMSIndoorDisplayDelegate {
func didChangeActiveBuilding(_ building: GMSIndoorBuilding?) {
guard let building = building else {
return
}
var sampleLevels: [SampleLevel] = []
sampleLevels.append(contentsOf: building.levels.map({ .actualLevel($0) }))
self.sampleLevels = sampleLevels
}
}

View File

@@ -0,0 +1,51 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class IndoorViewController: UIViewController {
let mapStyleOptions: [SampleMapStyle] = [.retro, .grayscale, .night, .normal]
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: 37.78318, longitude: -122.403874, zoom: 18)
let mapView = GMSMapView(frame: .zero, camera: camera)
mapView.settings.myLocationButton = true
return mapView
}()
override func loadView() {
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Style", style: .plain, target: self, action: #selector(changeMapStyle(_:)))
view = mapView
}
func alertAction(_ sampleMapStyle: SampleMapStyle) -> UIAlertAction {
return UIAlertAction(title: sampleMapStyle.description, style: .default) { [weak self] _ in
self?.mapView.mapStyle = sampleMapStyle.mapStyle
}
}
@objc func changeMapStyle(_ sender: UIBarButtonItem) {
let alert = UIAlertController(
title: "Select map style", message: nil, preferredStyle: .actionSheet)
for style in mapStyleOptions {
alert.addAction(alertAction(style))
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.popoverPresentationController?.barButtonItem = sender
present(alert, animated: true, completion: nil)
}
}

View File

@@ -0,0 +1,63 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class MapLayerViewController: UIViewController {
private let duration: TimeInterval = 2
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(target: .victoria, zoom: 4)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
mapView.isMyLocationEnabled = true
view = mapView
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Fly to My Location", style: .plain, target: self, action: #selector(tapMyLocation))
}
@objc func tapMyLocation() {
guard let location = mapView.myLocation, CLLocationCoordinate2DIsValid(location.coordinate)
else {
return
}
mapView.layer.cameraLatitude = location.coordinate.latitude
mapView.layer.cameraLongitude = location.coordinate.longitude
mapView.layer.cameraBearing = 0
// Access the GMSMapLayer directly to modify the following properties with a
// specified timing function and duration.
addMapViewAnimation(key: kGMSLayerCameraLatitudeKey, toValue: location.coordinate.latitude)
addMapViewAnimation(key: kGMSLayerCameraLongitudeKey, toValue: location.coordinate.longitude)
addMapViewAnimation(key: kGMSLayerCameraBearingKey, toValue: 0)
// Fly out to the minimum zoom and then zoom back to the current zoom!
let keyFrameAnimation = CAKeyframeAnimation(keyPath: kGMSLayerCameraZoomLevelKey)
keyFrameAnimation.duration = duration
let zoom = mapView.camera.zoom
keyFrameAnimation.values = [zoom, kGMSMinZoomLevel, zoom]
mapView.layer.add(keyFrameAnimation, forKey: kGMSLayerCameraZoomLevelKey)
}
func addMapViewAnimation(key: String, toValue: Double) {
let animation = CABasicAnimation(keyPath: key)
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
animation.toValue = toValue
mapView.layer.add(animation, forKey: key)
}
}

View File

@@ -0,0 +1,61 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class MapTypesViewController: UIViewController {
private let types: [GMSMapViewType] = [.normal, .satellite, .hybrid, .terrain]
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(target: .sydney, zoom: 12)
return GMSMapView(frame: .zero, camera: camera)
}()
private lazy var segmentedControl: UISegmentedControl = {
return UISegmentedControl(items: types.map { "\($0)" })
}()
override func loadView() {
view = mapView
}
override func viewDidLoad() {
super.viewDidLoad()
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(changeMapType), for: .valueChanged)
navigationItem.titleView = segmentedControl
}
@objc func changeMapType(_ sender: UISegmentedControl) {
mapView.mapType = types[sender.selectedSegmentIndex]
}
}
extension GMSMapViewType: CustomStringConvertible {
public var description: String {
switch self {
case .normal:
return "Normal"
case .satellite:
return "Satellite"
case .hybrid:
return "Hybrid"
case .terrain:
return "Terrain"
default:
return ""
}
}
}

View File

@@ -0,0 +1,109 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
enum ModeEnum: String {
case defaultMode = "Default"
case zoomedIn = "Zoomed in"
case zoomedOut = "Zoomed out"
case smallRange = "Small range"
init(index: UInt) {
switch index {
case 0: self = .defaultMode
case 1: self = .zoomedIn
case 2: self = .zoomedOut
case 3: self = .smallRange
default: self = .defaultMode
}
}
var minZoom: Float {
switch self {
case .zoomedIn:
return 18
case .smallRange:
return 10
default:
return kGMSMinZoomLevel
}
}
var maxZoom: Float {
switch self {
case .zoomedOut:
return 8
case .smallRange:
return 11.5
default:
return kGMSMaxZoomLevel
}
}
}
class MapZoomViewController: UIViewController {
private let backgroundColor = UIColor(white: 1, alpha: 0.8)
private let zoomRangeViewHeight: CGFloat = 30
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 6)
let mapView = GMSMapView(frame: .zero, camera: camera)
mapView.settings.scrollGestures = false
return mapView
}()
private lazy var zoomRangeView: UITextView = {
let view = UITextView()
view.text = ""
view.textAlignment = .center
view.backgroundColor = backgroundColor
view.autoresizingMask = .flexibleWidth
view.isEditable = false
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private var nextMode: UInt = 0
override func loadView() {
view = mapView
navigationController?.navigationBar.isTranslucent = false
// Add a display for the current zoom range restriction.
view.addSubview(zoomRangeView)
NSLayoutConstraint.activate([
zoomRangeView.topAnchor.constraint(equalTo: view.topAnchor),
zoomRangeView.heightAnchor.constraint(equalToConstant: zoomRangeViewHeight),
zoomRangeView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
zoomRangeView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
didTapNext()
// Add a button toggling through modes.
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .play, target: self, action: #selector(didTapNext))
}
@objc func didTapNext() {
let nextModeEnum = ModeEnum(index: nextMode)
mapView.setMinZoom(nextModeEnum.minZoom, maxZoom: nextModeEnum.maxZoom)
zoomRangeView.text = String(
format: "%@ (%.2f - %.2f)", nextModeEnum.rawValue, mapView.minZoom, mapView.maxZoom)
nextMode = (nextMode + 1) % 4
}
}

View File

@@ -0,0 +1,61 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
final class MarkerEventsViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -37.81969, longitude: 144.966085, zoom: 4)
return GMSMapView(frame: .zero, camera: camera)
}()
private var melbourneMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -37.81969, longitude: 144.966085))
override func loadView() {
let sydneyMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -33.8683, longitude: 151.2086))
sydneyMarker.map = mapView
melbourneMarker.map = mapView
mapView.delegate = self
view = mapView
}
}
extension MarkerEventsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
if marker == melbourneMarker {
return UIImageView(image: UIImage(named: "Icon"))
}
return nil
}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
// Animate to the marker
CATransaction.begin()
CATransaction.setAnimationDuration(3)
let camera = GMSCameraPosition(target: marker.position, zoom: 8, bearing: 50, viewingAngle: 60)
mapView.animate(to: camera)
CATransaction.commit()
// Melbourne marker has a InfoWindow so return false to allow markerInfoWindow to
// fire. Also check that the marker isn't already selected so that the InfoWindow
// doesn't close.
if marker == melbourneMarker && mapView.selectedMarker != melbourneMarker {
return false
}
return true
}
}

View File

@@ -0,0 +1,74 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
final class MarkerInfoWindowViewController: UIViewController {
private let sydneyMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -33.8683, longitude: 151.2086))
private let melbourneMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -37.81969, longitude: 144.966085))
private let brisbaneMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -27.4710107, longitude: 153.0234489))
private lazy var contentView: UIImageView = {
return UIImageView(image: UIImage(named: "aeroplane"))
}()
override func loadView() {
let cameraPosition = GMSCameraPosition(latitude: -37.81969, longitude: 144.966085, zoom: 4)
let mapView = GMSMapView(frame: .zero, camera: cameraPosition)
mapView.delegate = self
view = mapView
sydneyMarker.title = "Sydney"
sydneyMarker.snippet = "Population: 4,605,992"
sydneyMarker.map = mapView
melbourneMarker.title = "Melbourne"
melbourneMarker.snippet = "Population: 4,169,103"
melbourneMarker.map = mapView
brisbaneMarker.title = "Brisbane"
brisbaneMarker.snippet = "Population: 2,189,878"
brisbaneMarker.map = mapView
}
}
extension MarkerInfoWindowViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
if marker == sydneyMarker {
return contentView
}
return nil
}
func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView? {
if marker == brisbaneMarker {
return contentView
}
return nil
}
func mapView(_ mapView: GMSMapView, didCloseInfoWindowOf marker: GMSMarker) {
showToast(message: "Info window for marker \(marker.title ?? "") closed.")
}
func mapView(_ mapView: GMSMapView, didLongPressInfoWindowOf marker: GMSMarker) {
showToast(message: "Info window for marker \(marker.title ?? "") long pressed.")
}
}

View File

@@ -0,0 +1,125 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class PathIterator: IteratorProtocol {
let path: GMSPath
private var target: UInt
init(path: GMSPath) {
self.path = path
target = 0
}
func next() -> CLLocationCoordinate2D? {
target = (target + 1) % path.count()
return path.coordinate(at: target)
}
}
final class MarkerLayerViewController: UIViewController {
private var fadedMarker: GMSMarker? {
didSet {
oldValue?.opacity = 1
fadedMarker?.opacity = 0.5
}
}
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: 50.6042, longitude: 3.9599, zoom: 5)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
mapView.isMyLocationEnabled = true
view = mapView
mapView.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
// Creates a plane that flies to several airports around western Europe.
var path = GMSMutablePath()
path.addLatitude(52.310683, longitude: 4.765121)
path.addLatitude(51.471386, longitude: -0.457148)
path.addLatitude(49.01378, longitude: 2.5542943)
path.addLatitude(50.036194, longitude: 8.554519)
var marker = GMSMarker(position: path.coordinate(at: 0))
marker.icon = UIImage(named: "aeroplane")
marker.groundAnchor = CGPoint(x: 0.5, y: 0.5)
marker.isFlat = true
marker.map = mapView
marker.userData = PathIterator(path: path)
animateToNextCoordinate(marker)
// Creates a boat that moves around the Baltic Sea.
path = GMSMutablePath()
path.addLatitude(57.598335, longitude: 11.290512)
path.addLatitude(55.665193, longitude: 10.741196)
path.addLatitude(55.065787, longitude: 11.083488)
path.addLatitude(54.699234, longitude: 10.863762)
path.addLatitude(54.482805, longitude: 12.061272)
path.addLatitude(55.819802, longitude: 16.148186)
path.addLatitude(54.927142, longitude: 16.455803)
path.addLatitude(54.482805, longitude: 12.061272)
path.addLatitude(54.699234, longitude: 10.863762)
path.addLatitude(55.065787, longitude: 11.083488)
path.addLatitude(55.665193, longitude: 10.741196)
marker = GMSMarker(position: path.coordinate(at: 0))
marker.icon = UIImage(named: "boat")
marker.map = mapView
marker.userData = PathIterator(path: path)
animateToNextCoordinate(marker)
}
func animateToNextCoordinate(_ marker: GMSMarker) {
guard let coordinateList = marker.userData as? PathIterator else { return }
guard let coordinate = coordinateList.next() else { return }
let previous = marker.position
let heading = GMSGeometryHeading(previous, coordinate)
let distance = GMSGeometryDistance(previous, coordinate)
// If this marker is flat, implicitly trigger a change in rotation, which will finish quickly.
if marker.isFlat {
marker.rotation = heading
}
// Use CATransaction to set a custom duration for this animation. By default, changes to the
// position are already animated, but with a very short default duration. When the animation is
// complete, trigger another animation step.
CATransaction.begin()
CATransaction.setAnimationDuration(distance / (50 * 1000)) // custom duration, 50km/sec
CATransaction.setCompletionBlock {
self.animateToNextCoordinate(marker)
}
marker.position = coordinate
CATransaction.commit()
}
}
extension MarkerLayerViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
fadedMarker = marker
return true
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
fadedMarker = nil
}
}

View File

@@ -0,0 +1,64 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
// Sample code for adding a marker.
class MarkersViewController: UIViewController {
private lazy var sydneyMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -33.8683, longitude: 151.2086))
private lazy var melbourneMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -37.81969, longitude: 144.966085))
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -37.81969, longitude: 144.966085, zoom: 4)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
view = mapView
sydneyMarker.title = "Sydney"
sydneyMarker.snippet = "Population: 4,605,992"
sydneyMarker.isFlat = false
sydneyMarker.rotation = 30
print("sydneyMarker: \(sydneyMarker)")
let australiaMarker = GMSMarker(
position: CLLocationCoordinate2D(latitude: -27.994401, longitude: 140.07019))
australiaMarker.title = "Australia"
australiaMarker.appearAnimation = .pop
australiaMarker.isFlat = true
australiaMarker.isDraggable = true
australiaMarker.groundAnchor = CGPoint(x: 0.5, y: 0.5)
australiaMarker.icon = UIImage(named: "australia")
australiaMarker.map = mapView
mapView.selectedMarker = sydneyMarker
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .add, target: self, action: #selector(tapAdd))
}
@objc func tapAdd() {
if sydneyMarker.map == nil {
sydneyMarker.map = mapView
} else {
sydneyMarker.map = nil
}
melbourneMarker.title = "Melbourne"
melbourneMarker.snippet = "Population: 4,169,103"
melbourneMarker.map = mapView
}
}

View File

@@ -0,0 +1,69 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class MyLocationViewController: UIViewController {
private let cameraLatitude: CLLocationDegrees = -33.868
private let cameraLongitude: CLLocationDegrees = 151.2086
private let cameraZoom: Float = 12
lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(
latitude: cameraLatitude, longitude: cameraLongitude, zoom: cameraZoom)
return GMSMapView(frame: .zero, camera: camera)
}()
var observation: NSKeyValueObservation?
var location: CLLocation? {
didSet {
guard oldValue == nil, let firstLocation = location else { return }
mapView.camera = GMSCameraPosition(target: firstLocation.coordinate, zoom: 14)
}
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.settings.compassButton = true
mapView.settings.myLocationButton = true
mapView.isMyLocationEnabled = true
view = mapView
// Listen to the myLocation property of GMSMapView.
observation = mapView.observe(\.myLocation, options: [.new]) {
[weak self] mapView, _ in
self?.location = mapView.myLocation
}
}
deinit {
observation?.invalidate()
}
}
extension MyLocationViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTapMyLocation location: CLLocationCoordinate2D) {
let alert = UIAlertController(
title: "Location Tapped",
message: "Current location: <\(location.latitude), \(location.longitude)>",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
present(alert, animated: true)
}
}

View File

@@ -0,0 +1,124 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class PaddingBehaviorViewController: UIViewController {
private static let panoramaCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(
latitude: 40.761388, longitude: -73.978133)
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 6)
let mapView = GMSMapView(frame: .zero, camera: camera)
mapView.padding = UIEdgeInsets(top: 0, left: 20, bottom: 40, right: 60)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return mapView
}()
private lazy var panoramaView: GMSPanoramaView = GMSPanoramaView()
lazy private var statusLabel: UILabel = UILabel()
lazy private var changeBehaviorButton: UIButton = UIButton(type: .system)
lazy private var toggleViewButton: UIBarButtonItem = UIBarButtonItem(
title: "Toggle View", style: .plain, target: self, action: #selector(toggleViewType))
lazy private var toggleFrameButton: UIButton = UIButton(type: .system)
var hasShrunk = false
override func viewDidLoad() {
super.viewDidLoad()
mapView.frame = view.bounds
view.addSubview(mapView)
// Add status label.
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let navigationHeight = navigationController?.navigationBar.frame.height ?? 0
let topYOffset = statusBarHeight + navigationHeight
statusLabel.frame = CGRect(x: 30, y: topYOffset, width: 0, height: 30)
statusLabel.textColor = .brown
statusLabel.textAlignment = .left
statusLabel.text = "Behavior: Always"
statusLabel.sizeToFit()
// Add behavior modifier button.
changeBehaviorButton.frame = CGRect(x: 30, y: 30 + topYOffset, width: 0, height: 0)
changeBehaviorButton.setTitle("Next Behavior", for: .normal)
changeBehaviorButton.sizeToFit()
changeBehaviorButton.addTarget(self, action: #selector(nextBehavior), for: .touchUpInside)
// Add frame animation button.
navigationItem.rightBarButtonItem = toggleViewButton
// Add change view type button.
toggleFrameButton.frame = CGRect(x: 30, y: 60 + topYOffset, width: 0, height: 0)
toggleFrameButton.setTitle("Animate Frame", for: .normal)
toggleFrameButton.sizeToFit()
toggleFrameButton.addTarget(self, action: #selector(toggleFrame), for: .touchUpInside)
mapView.addSubview(statusLabel)
mapView.addSubview(changeBehaviorButton)
mapView.addSubview(toggleFrameButton)
hasShrunk = false
// Pre-load PanoramaView
panoramaView = GMSPanoramaView.panorama(
withFrame: view.bounds, nearCoordinate: PaddingBehaviorViewController.panoramaCoordinate)
panoramaView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
@objc func toggleFrame() {
let size = view.bounds.size
let point = view.bounds.origin
UIView.animate(withDuration: 2) { [unowned self] in
if self.hasShrunk {
self.mapView.frame = self.view.bounds
self.panoramaView.frame = self.mapView.frame
} else {
self.mapView.frame = CGRect(
x: point.x, y: point.y, width: size.width / 2, height: size.height / 2)
self.panoramaView.frame = self.mapView.frame
}
self.hasShrunk = !self.hasShrunk
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
}
@objc func toggleViewType() {
if view.subviews.contains(mapView) {
mapView.removeFromSuperview()
view.addSubview(panoramaView)
panoramaView.addSubview(toggleFrameButton)
} else {
panoramaView.removeFromSuperview()
view.addSubview(mapView)
mapView.addSubview(toggleFrameButton)
}
}
@objc func nextBehavior() {
switch mapView.paddingAdjustmentBehavior {
case .always:
mapView.paddingAdjustmentBehavior = .automatic
statusLabel.text = "Behavior: Automatic"
case .automatic:
mapView.paddingAdjustmentBehavior = .never
statusLabel.text = "Behavior: Never"
default:
mapView.paddingAdjustmentBehavior = .always
statusLabel.text = "Behavior: Always"
}
}
}

View File

@@ -0,0 +1,87 @@
// Copyright 2022 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
final class PanoramaServiceController: UIViewController {
private let markerLocation = CLLocationCoordinate2D.sydney
private var mySubview = UIView(frame: .zero)
private var statusLabel = UILabel(frame: .zero)
private var result = UITextView(frame: .zero)
private var panoService: GMSPanoramaService?
private var requestCount = 0
private var responseCount = 0
override func loadView() {
navigationController?.navigationBar.isTranslucent = false
view = mySubview
statusLabel.alpha = 1.0
statusLabel.backgroundColor = .blue
statusLabel.textColor = .white
statusLabel.textAlignment = .center
statusLabel.text = "Service Never Called"
view.addSubview(statusLabel)
statusLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(result)
result.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
statusLabel.topAnchor.constraint(equalTo: view.topAnchor),
statusLabel.heightAnchor.constraint(equalToConstant: 30),
statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
result.topAnchor.constraint(equalTo: statusLabel.bottomAnchor),
result.bottomAnchor.constraint(equalTo: view.bottomAnchor),
result.leadingAnchor.constraint(equalTo: view.leadingAnchor),
result.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
}
override func viewDidAppear(_ animated: Bool) {
if panoService == nil {
panoService = GMSPanoramaService()
statusLabel.text = "Service initialized \(panoService?.description ?? "nil")"
}
requestCount += 1
panoService?.requestPanoramaNearCoordinate(
markerLocation,
radius: 300, // meters
source: .outside
) {
pano, err in
self.responseCount += 1
self.statusLabel.text =
"Callback invoked \(self.responseCount) time(s) out of \(self.requestCount) requests."
if let pano = pano {
self.result.text = [
"id: \(pano.panoramaID)",
"#neighbors: \(pano.links.count)",
"coordinate: \(pano.coordinate)",
"description: \(pano.description)",
"debugDescription: \(pano.debugDescription)",
].joined(separator: "\n")
} else {
self.result.text = "<nil>"
}
}
super.viewWillAppear(animated)
}
}

View File

@@ -0,0 +1,69 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class PanoramaViewController: UIViewController {
private let markerLocation = CLLocationCoordinate2D(latitude: 40.761455, longitude: -73.977814)
private var panoramaView = GMSPanoramaView(frame: .zero)
private var statusLabel = UILabel(frame: .zero)
private var configured = false
override func loadView() {
navigationController?.navigationBar.isTranslucent = false
panoramaView.moveNearCoordinate(.newYork)
panoramaView.backgroundColor = .gray
panoramaView.delegate = self
view = panoramaView
statusLabel.alpha = 0.0
statusLabel.backgroundColor = .blue
statusLabel.textColor = .white
statusLabel.textAlignment = .center
view.addSubview(statusLabel)
statusLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
statusLabel.topAnchor.constraint(equalTo: view.topAnchor),
statusLabel.heightAnchor.constraint(equalToConstant: 30),
statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
}
}
extension PanoramaViewController: GMSPanoramaViewDelegate {
func panoramaView(_ panoramaView: GMSPanoramaView, didMove camera: GMSPanoramaCamera) {
print("Camera:\(camera.orientation.heading), \(camera.orientation.pitch), \(camera.zoom)")
}
func panoramaView(_ view: GMSPanoramaView, didMoveTo panorama: GMSPanorama?) {
if configured { return }
let marker = GMSMarker(position: markerLocation)
marker.icon = GMSMarker.markerImage(with: .purple)
marker.panoramaView = panoramaView
let heading = GMSGeometryHeading(.newYork, markerLocation)
panoramaView.camera = GMSPanoramaCamera(heading: heading, pitch: 0, zoom: 1)
configured = true
}
func panoramaViewDidStartRendering(_ panoramaView: GMSPanoramaView) {
statusLabel.alpha = 0.8
statusLabel.text = "Rendering"
}
func panoramaViewDidFinishRendering(_ panoramaView: GMSPanoramaView) {
statusLabel.alpha = 0
}
}

View File

@@ -0,0 +1,275 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
final class PolygonsViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let cameraPosition = GMSCameraPosition(latitude: 39.13006, longitude: -77.508545, zoom: 4)
return GMSMapView(frame: .zero, camera: cameraPosition)
}()
override func loadView() {
mapView.delegate = self
view = mapView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Create renderer related objects after view appears, so a renderer will be available;
let polygon = GMSPolygon()
polygon.path = GMSPath.newYorkState()
polygon.holes = [GMSPath.newYorkStateHole()]
polygon.title = "New York"
polygon.fillColor = UIColor(red: 0.25, green: 0, blue: 0, alpha: 0.2)
polygon.strokeColor = .black
polygon.strokeWidth = 2
polygon.isTappable = true
polygon.map = mapView
// Copy the existing polygon and its settings and use it as a base for the
// second polygon.
let carolina = polygon.copy() as! GMSPolygon
carolina.title = "North Carolina"
carolina.path = GMSPath.northCarolina()
carolina.fillColor = UIColor(red: 0, green: 0.25, blue: 0, alpha: 0.5)
carolina.map = mapView
}
}
extension GMSPath {
static func newYorkState() -> GMSPath {
let data: [[CLLocationDegrees]] = [
[42.5142, -79.7624],
[42.7783, -79.0672],
[42.8508, -78.9313],
[42.9061, -78.9024],
[42.9554, -78.9313],
[42.9584, -78.9656],
[42.9886, -79.0219],
[43.0568, -79.0027],
[43.0769, -79.0727],
[43.1220, -79.0713],
[43.1441, -79.0302],
[43.1801, -79.0576],
[43.2482, -79.0604],
[43.2812, -79.0837],
[43.4509, -79.2004],
[43.6311, -78.6909],
[43.6321, -76.7958],
[43.9987, -76.4978],
[44.0965, -76.4388],
[44.1349, -76.3536],
[44.1989, -76.3124],
[44.2049, -76.2437],
[44.2413, -76.1655],
[44.2973, -76.1353],
[44.3327, -76.0474],
[44.3553, -75.9856],
[44.3749, -75.9196],
[44.3994, -75.8730],
[44.4308, -75.8221],
[44.4740, -75.8098],
[44.5425, -75.7288],
[44.6647, -75.5585],
[44.7672, -75.4088],
[44.8101, -75.3442],
[44.8383, -75.3058],
[44.8676, -75.2399],
[44.9211, -75.1204],
[44.9609, -74.9995],
[44.9803, -74.9899],
[44.9852, -74.9103],
[45.0017, -74.8856],
[45.0153, -74.8306],
[45.0046, -74.7633],
[45.0027, -74.7070],
[45.0007, -74.5642],
[44.9920, -74.1467],
[45.0037, -73.7306],
[45.0085, -73.4203],
[45.0109, -73.3430],
[44.9874, -73.3547],
[44.9648, -73.3379],
[44.9160, -73.3396],
[44.8354, -73.3739],
[44.8013, -73.3324],
[44.7419, -73.3667],
[44.6139, -73.3873],
[44.5787, -73.3736],
[44.4916, -73.3049],
[44.4289, -73.2953],
[44.3513, -73.3365],
[44.2757, -73.3118],
[44.1980, -73.3818],
[44.1142, -73.4079],
[44.0511, -73.4367],
[44.0165, -73.4065],
[43.9375, -73.4079],
[43.8771, -73.3749],
[43.8167, -73.3914],
[43.7790, -73.3557],
[43.6460, -73.4244],
[43.5893, -73.4340],
[43.5655, -73.3969],
[43.6112, -73.3818],
[43.6271, -73.3049],
[43.5764, -73.3063],
[43.5675, -73.2582],
[43.5227, -73.2445],
[43.2582, -73.2582],
[42.9715, -73.2733],
[42.8004, -73.2898],
[42.7460, -73.2664],
[42.4630, -73.3708],
[42.0840, -73.5095],
[42.0218, -73.4903],
[41.8808, -73.4999],
[41.2953, -73.5535],
[41.2128, -73.4834],
[41.1011, -73.7275],
[41.0237, -73.6644],
[40.9851, -73.6578],
[40.9509, -73.6132],
[41.1869, -72.4823],
[41.2551, -72.0950],
[41.3005, -71.9714],
[41.3108, -71.9193],
[41.1838, -71.7915],
[41.1249, -71.7929],
[41.0462, -71.7517],
[40.6306, -72.9465],
[40.5368, -73.4628],
[40.4887, -73.8885],
[40.5232, -73.9490],
[40.4772, -74.2271],
[40.4861, -74.2532],
[40.6468, -74.1866],
[40.6556, -74.0547],
[40.7618, -74.0156],
[40.8699, -73.9421],
[40.9980, -73.8934],
[41.0343, -73.9854],
[41.3268, -74.6274],
[41.3583, -74.7084],
[41.3811, -74.7101],
[41.4386, -74.8265],
[41.5075, -74.9913],
[41.6000, -75.0668],
[41.6719, -75.0366],
[41.7672, -75.0545],
[41.8808, -75.1945],
[42.0013, -75.3552],
[42.0003, -75.4266],
[42.0013, -77.0306],
[41.9993, -79.7250],
[42.0003, -79.7621],
[42.1827, -79.7621],
[42.5146, -79.7621],
]
let path = GMSMutablePath()
for degrees in data {
path.addLatitude(degrees[0], longitude: degrees[1])
}
return path
}
static func newYorkStateHole() -> GMSPath {
let path = GMSMutablePath()
path.addLatitude(43.5000, longitude: -76.3651)
path.addLatitude(43.5000, longitude: -74.3651)
path.addLatitude(42.0000, longitude: -74.3651)
return path
}
static func northCarolina() -> GMSPath {
let path = GMSMutablePath()
let data = [
[33.7963, -78.4850],
[34.8037, -79.6742],
[34.8206, -80.8003],
[34.9377, -80.7880],
[35.1019, -80.9377],
[35.0356, -81.0379],
[35.1457, -81.0324],
[35.1660, -81.3867],
[35.1985, -82.2739],
[35.2041, -82.3933],
[35.0637, -82.7765],
[35.0817, -82.7861],
[34.9996, -83.1075],
[34.9918, -83.6183],
[34.9918, -84.3201],
[35.2131, -84.2885],
[35.2680, -84.2226],
[35.2310, -84.1113],
[35.2815, -84.0454],
[35.4058, -84.0248],
[35.4719, -83.9424],
[35.5166, -83.8559],
[35.5512, -83.6938],
[35.5680, -83.5181],
[35.6327, -83.3849],
[35.7142, -83.2475],
[35.7799, -82.9962],
[35.8445, -82.9276],
[35.9224, -82.8191],
[35.9958, -82.7710],
[36.0613, -82.6419],
[35.9702, -82.6103],
[35.9547, -82.5677],
[36.0236, -82.4730],
[36.0669, -82.4194],
[36.1168, -82.3535],
[36.1345, -82.2862],
[36.1467, -82.1461],
[36.1035, -82.1228],
[36.1268, -82.0267],
[36.2797, -81.9360],
[36.3527, -81.7987],
[36.3361, -81.7081],
[36.5880, -81.6724],
[36.5659, -80.7234],
[36.5438, -80.2977],
[36.5449, -79.6729],
[36.5449, -77.2559],
[36.5505, -75.7562],
[36.3129, -75.7068],
[35.7131, -75.4129],
[35.2041, -75.4720],
[34.9794, -76.0748],
[34.5258, -76.4951],
[34.5880, -76.8109],
[34.5314, -77.1378],
[34.3910, -77.4481],
[34.0481, -77.7983],
[33.7666, -77.9260],
[33.7963, -78.4863],
]
for degrees in data {
path.addLatitude(degrees[0], longitude: degrees[1])
}
return path
}
}
extension PolygonsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {
// When a polygon is tapped, randomly change its fill color to a new hue.
guard let polygon = overlay as? GMSPolygon else { return }
polygon.fillColor = UIColor(
hue: CGFloat.random(in: 0..<1), saturation: 1, brightness: 1, alpha: 0.5)
}
}

View File

@@ -0,0 +1,72 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
final class PolylinesViewController: UIViewController {
private lazy var styles: [GMSStrokeStyle] = {
let greenStyle = GMSStrokeStyle.gradient(from: .green, to: UIColor.green.withAlphaComponent(0))
let redStyle = GMSStrokeStyle.gradient(from: UIColor.red.withAlphaComponent(0), to: .red)
return [greenStyle, redStyle, GMSStrokeStyle.solidColor(UIColor(white: 0, alpha: 0))]
}()
private var pathLength: Double = 0
private var pos: Double = 0
private var polylines: [GMSPolyline] = []
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -30, longitude: -175, zoom: 3)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
view = mapView
mapView.accessibilityElementsHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
var path = GMSMutablePath()
path.addLatitude(-33.866901, longitude: 151.195988)
path.addLatitude(-18, longitude: 179)
path.addLatitude(21.291982, longitude: -157.821856)
path.addLatitude(37.423802, longitude: -122.091859)
path.addLatitude(-12, longitude: -77)
path.addLatitude(-33.866901, longitude: 151.195988)
path = path.pathOffset(byLatitude: -30, longitude: 0)
pathLength = path.length(of: .geodesic) / 21
for i in 0..<30 {
let polyline = GMSPolyline(path: path.pathOffset(byLatitude: Double(i) * 1.5, longitude: 0))
polyline.strokeWidth = 8
polyline.geodesic = true
polyline.map = mapView
polylines.append(polyline)
}
animatePath()
}
// Updates the path style every 0.1 seconds.
private func animatePath() {
polylines.forEach {
if let path = $0.path {
$0.spans = GMSStyleSpansOffset(path, styles, [NSNumber(value: pathLength)], .geodesic, pos)
}
}
pos -= 50000
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.animatePath()
}
}
}

View File

@@ -0,0 +1,55 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
enum SampleLevel: Equatable {
case fakeGroundLevel
case actualLevel(GMSIndoorLevel)
init(indoorLevel: GMSIndoorLevel?) {
if let level = indoorLevel {
self = .actualLevel(level)
} else {
self = .fakeGroundLevel
}
}
var name: String {
switch self {
case .fakeGroundLevel:
return "\u{2014}" // use an em dash for 'above ground'
case .actualLevel(let level):
return level.name ?? ""
}
}
var shortName: String? {
switch self {
case .fakeGroundLevel:
return nil
case .actualLevel(let level):
return level.shortName ?? ""
}
}
var indoorLevel: GMSIndoorLevel? {
switch self {
case .fakeGroundLevel:
return nil
case .actualLevel(let level):
return level
}
}
}

View File

@@ -0,0 +1,75 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
enum SampleMapStyle: CustomStringConvertible, CaseIterable {
case normal
case retro
case grayscale
case night
case clean
private static let mapStyleJSON = """
[
{
"featureType" : "poi.business",
"elementType" : "all",
"stylers" : [
{
"visibility" : "off"
}
]
},
{
"featureType" : "transit",
"elementType" : "labels.icon",
"stylers" : [
{
"visibility" : "off"
}
]
}
]
"""
var description: String {
switch self {
case .normal:
return "Normal"
case .retro:
return "Retro"
case .grayscale:
return "Grayscale"
case .night:
return "Night"
case .clean:
return "No business points of interest, no transit"
}
}
var mapStyle: GMSMapStyle? {
switch self {
case .normal:
return nil
case .retro:
return try? GMSMapStyle(named: "mapstyle-retro")
case .grayscale:
return try? GMSMapStyle(named: "mapstyle-silver")
case .night:
return try? GMSMapStyle(named: "mapstyle-night")
case .clean:
return try? GMSMapStyle(jsonString: SampleMapStyle.mapStyleJSON)
}
}
}

View File

@@ -0,0 +1,100 @@
// Copyright 2022 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import UIKit
struct Sample {
let viewControllerClass: UIViewController.Type
let title: String
}
struct Section {
let name: String
let samples: [Sample]
}
enum Samples {
static func allSamples() -> [Section] {
let mapSamples = [
Sample(viewControllerClass: BasicMapViewController.self, title: "Basic Map"),
Sample(viewControllerClass: MapTypesViewController.self, title: "Map Types"),
Sample(viewControllerClass: StyledMapViewController.self, title: "Styled Map"),
Sample(viewControllerClass: TrafficMapViewController.self, title: "Traffic Layer"),
Sample(viewControllerClass: MyLocationViewController.self, title: "My Location"),
Sample(viewControllerClass: IndoorViewController.self, title: "Indoor"),
Sample(
viewControllerClass: CustomIndoorViewController.self,
title: "Indoor with Custom Level Select"),
Sample(
viewControllerClass: IndoorMuseumNavigationViewController.self,
title: "Indoor Museum Navigator"),
Sample(viewControllerClass: GestureControlViewController.self, title: "Gesture Control"),
Sample(viewControllerClass: SnapshotReadyViewController.self, title: "Snapshot Ready"),
Sample(viewControllerClass: DoubleMapViewController.self, title: "Two Maps"),
Sample(viewControllerClass: VisibleRegionViewController.self, title: "Visible Regions"),
Sample(viewControllerClass: MapZoomViewController.self, title: "Min/Max Zoom"),
Sample(viewControllerClass: FrameRateViewController.self, title: "Frame Rate"),
Sample(viewControllerClass: PaddingBehaviorViewController.self, title: "Padding Behavior"),
]
let overlaySamples = [
Sample(viewControllerClass: MarkersViewController.self, title: "Markers"),
Sample(viewControllerClass: CustomMarkersViewController.self, title: "Custom Markers"),
Sample(viewControllerClass: AnimatedUIViewMarkerViewController.self, title: "UIView Markers"),
Sample(viewControllerClass: MarkerEventsViewController.self, title: "Marker Events"),
Sample(viewControllerClass: MarkerLayerViewController.self, title: "Marker Layer"),
Sample(
viewControllerClass: MarkerInfoWindowViewController.self, title: "Custom Info Windows"),
Sample(viewControllerClass: PolygonsViewController.self, title: "Polygons"),
Sample(viewControllerClass: PolylinesViewController.self, title: "Polylines"),
Sample(viewControllerClass: GroundOverlayViewController.self, title: "Ground Overlays"),
Sample(viewControllerClass: TileLayerViewController.self, title: "Tile Layers"),
Sample(
viewControllerClass: AnimatedCurrentLocationViewController.self,
title: "Animated Current Location"),
Sample(
viewControllerClass: GradientPolylinesViewController.self, title: "Gradient Polylines"),
]
let datadrivenStylingSamples = [
Sample(
viewControllerClass: DataDrivenStylingBasicViewController.self, title: "Basic"),
Sample(
viewControllerClass: DataDrivenStylingEventsViewController.self, title: "Events"),
Sample(
viewControllerClass: DataDrivenStylingSearchViewController.self,
title: "Places from text search"),
]
let panoramaSamples = [
Sample(viewControllerClass: PanoramaServiceController.self, title: "Panorama Service"),
Sample(viewControllerClass: PanoramaViewController.self, title: "Street View"),
Sample(viewControllerClass: FixedPanoramaViewController.self, title: "Fixed Street View"),
]
let cameraSamples = [
Sample(viewControllerClass: FitBoundsViewController.self, title: "Fit Bounds"),
Sample(viewControllerClass: CameraViewController.self, title: "Camera Animation"),
Sample(viewControllerClass: MapLayerViewController.self, title: "Map Layer"),
]
let serviceSamples = [
Sample(viewControllerClass: GeocoderViewController.self, title: "Geocoder"),
Sample(
viewControllerClass: StructuredGeocoderViewController.self, title: "Structured Geocoder"),
]
return [
Section(name: "Map", samples: mapSamples),
Section(name: "Panorama", samples: panoramaSamples),
Section(name: "Overlays", samples: overlaySamples),
Section(name: "Data-driven Styling", samples: datadrivenStylingSamples),
Section(name: "Camera", samples: cameraSamples),
Section(name: "Services", samples: serviceSamples),
]
}
}

View File

@@ -0,0 +1,118 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class SnapshotReadyViewController: UIViewController {
lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 6)
return GMSMapView(frame: .zero, camera: camera)
}()
private lazy var statusLabel: UILabel = UILabel()
private lazy var waitButton: UIBarButtonItem = UIBarButtonItem()
private var isAwaitingSnapshot = false {
didSet {
waitButton.isEnabled = !isAwaitingSnapshot
if isAwaitingSnapshot {
waitButton.title = "Waiting"
} else {
waitButton.title = "Wait for snapshot"
}
}
}
override func loadView() {
view = mapView
navigationController?.navigationBar.isTranslucent = false
mapView.delegate = self
// Add status label, initially hidden.
statusLabel.alpha = 0
statusLabel.autoresizingMask = .flexibleWidth
statusLabel.backgroundColor = .blue
statusLabel.textColor = .white
statusLabel.textAlignment = .center
view.addSubview(statusLabel)
statusLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
statusLabel.leftAnchor.constraint(equalTo: view.leftAnchor),
statusLabel.rightAnchor.constraint(equalTo: view.rightAnchor),
statusLabel.heightAnchor.constraint(equalToConstant: 30),
])
NSLayoutConstraint.activate([
statusLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
])
// Add a wait button to signify on the next SnapshotReady event, a screenshot of the map will
// be taken.
waitButton = UIBarButtonItem(
title: "Wait for snapshot", style: .plain, target: self, action: #selector(didTapWait))
navigationItem.rightBarButtonItem = waitButton
}
@objc func didTapWait() {
isAwaitingSnapshot = true
}
func takeSnapshot() {
// Take a snapshot of the map.
UIGraphicsBeginImageContextWithOptions(mapView.bounds.size, true, 0)
mapView.drawHierarchy(in: mapView.bounds, afterScreenUpdates: true)
let mapSnapshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Put snapshot image into an UIImageView and overlay on top of map.
let imageView = UIImageView(image: mapSnapshot)
imageView.layer.borderColor = UIColor.red.cgColor
imageView.layer.borderWidth = 10
mapView.addSubview(imageView)
// Remove imageView after 1 second.
DispatchQueue.main.asyncAfter(
deadline: .now() + 1
) {
UIView.animate(
withDuration: 1,
animations: {
imageView.alpha = 0
},
completion: { _ in
imageView.removeFromSuperview()
})
}
}
}
extension SnapshotReadyViewController: GMSMapViewDelegate {
func mapViewSnapshotReady(_ mapView: GMSMapView) {
if isAwaitingSnapshot {
isAwaitingSnapshot = false
takeSnapshot()
}
statusLabel.alpha = 0.8
statusLabel.text = "Snapshot Ready"
// Remove status label after 1 second.
DispatchQueue.main.asyncAfter(
deadline: .now() + 1
) {
self.statusLabel.alpha = 0
}
}
}

View File

@@ -0,0 +1,71 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
// Sample code for GeoCoder service.
class StructuredGeocoderViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12)
return GMSMapView(frame: .zero, camera: camera)
}()
private lazy var geocoder = GMSGeocoder()
override func loadView() {
view = mapView
mapView.delegate = self
}
}
extension StructuredGeocoderViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
// On a long press, reverse geocode this location.
geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
guard let address = response?.firstResult() else {
let errorMessage = error.map { String(describing: $0) } ?? "<no error>"
print(
"""
Could not reverse geocode point (\(coordinate.latitude), \(coordinate.longitude)): \
\(errorMessage)
"""
)
return
}
print("Geocoder result: \(address)")
let marker = GMSMarker(position: address.coordinate)
marker.appearAnimation = .pop
marker.map = mapView
marker.title = address.thoroughfare
mapView.selectedMarker = marker
var snippet = ""
if let subLocality = address.subLocality {
snippet.append("subLocality: \(subLocality)\n")
}
if let locality = address.locality {
snippet.append("locality: \(locality)\n")
}
if let administrativeArea = address.administrativeArea {
snippet.append("administrativeArea: \(administrativeArea)\n")
}
if let country = address.country {
snippet.append("country: \(country)\n")
}
marker.snippet = snippet
}
}
}

View File

@@ -0,0 +1,52 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class StyledMapViewController: UIViewController {
lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
view = mapView
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Style", style: .plain, target: self, action: #selector(changeMapStyle))
updateUI(style: .retro)
}
func updateUI(style: SampleMapStyle) {
navigationItem.title = "\(style)"
mapView.mapStyle = style.mapStyle
}
@objc func changeMapStyle(_ sender: UIBarButtonItem) {
let alert = UIAlertController(
title: "Select map style", message: nil, preferredStyle: .actionSheet)
for style in SampleMapStyle.allCases {
alert.addAction(
UIAlertAction(
title: style.description, style: .default
) { _ in
self.updateUI(style: style)
})
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.popoverPresentationController?.barButtonItem = sender
present(alert, animated: true)
}
}

View File

@@ -0,0 +1,67 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
final class TileLayerViewController: UIViewController {
private var selectedIndex = 0 {
didSet {
updateTileLayer()
}
}
private var tileLayer: GMSURLTileLayer?
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: 37.78318, longitude: -122.403874, zoom: 18)
return GMSMapView(frame: .zero, camera: camera)
}()
private lazy var segmentedControl: UISegmentedControl = {
let floorNames = ["1", "2", "3"]
return UISegmentedControl(items: floorNames)
}()
override func loadView() {
mapView.isBuildingsEnabled = false
mapView.isIndoorEnabled = false
view = mapView
// The possible floors that might be shown.
segmentedControl.selectedSegmentIndex = 0
selectedIndex = 0
navigationItem.titleView = segmentedControl
// Listen to touch events on the UISegmentedControl, force initial update.
segmentedControl.addTarget(self, action: #selector(changeFloor), for: .valueChanged)
changeFloor()
}
@objc func changeFloor() {
guard segmentedControl.selectedSegmentIndex != selectedIndex else { return }
selectedIndex = segmentedControl.selectedSegmentIndex
}
func updateTileLayer() {
// Clear existing tileLayer, if any.
tileLayer?.map = nil
// Create a new GMSTileLayer with the new floor choice.
tileLayer = GMSURLTileLayer(urlConstructor: { (x: UInt, y: UInt, zoom: UInt) -> URL? in
return URL(
string:
"https://www.gstatic.com/io2010maps/tiles/9/L\(self.selectedIndex + 1)_\(zoom)_\(x)_\(y).png"
)
})
tileLayer?.map = mapView
}
}

View File

@@ -0,0 +1,30 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class TrafficMapViewController: UIViewController {
private var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12)
let mapView = GMSMapView(frame: .zero, camera: camera)
mapView.isTrafficEnabled = true
return mapView
}()
override func loadView() {
view = mapView
}
}

View File

@@ -0,0 +1,48 @@
// Copyright 2023 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import UIKit
extension UIViewController {
public func showToast(message: String) {
let toast = UIAlertController(title: nil, message: message, preferredStyle: .alert)
present(
toast, animated: true,
completion: {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) {
toast.dismiss(animated: true)
}
})
}
public func promptForMapID(description: String, completion: @escaping (String) -> Void) {
let alert = UIAlertController(
title: "Map ID to use",
message: "Enter a Map ID configured from the Cloud Console \(description)",
preferredStyle: .alert)
alert.addAction(
UIAlertAction(
title: "Cancel", style: .cancel,
handler: { _ in
completion("")
}))
alert.addAction(
UIAlertAction(
title: "Confirm", style: .default,
handler: { _ in
completion(alert.textFields?.first?.text ?? "")
}))
alert.addTextField(configurationHandler: { $0.placeholder = "Map ID" })
self.present(alert, animated: true, completion: nil)
}
}

View File

@@ -0,0 +1,69 @@
// Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class VisibleRegionViewController: UIViewController {
static let overlayHeight: CGFloat = 140
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -37.81969, longitude: 144.966085, zoom: 4)
let mapView = GMSMapView(frame: .zero, camera: camera)
mapView.settings.myLocationButton = true
mapView.isMyLocationEnabled = true
mapView.padding = UIEdgeInsets(
top: 0, left: 0, bottom: VisibleRegionViewController.overlayHeight, right: 0)
return mapView
}()
private lazy var overlay: UIView = {
let overlay = UIView(frame: .zero)
overlay.backgroundColor = UIColor(hue: 0, saturation: 1, brightness: 1, alpha: 0.5)
return overlay
}()
private lazy var flyInButton: UIBarButtonItem = {
return UIBarButtonItem(
title: "Toggle Overlay", style: .plain, target: self, action: #selector(didTapToggleOverlay))
}()
override func loadView() {
view = mapView
navigationItem.rightBarButtonItem = flyInButton
let overlayFrame = CGRect(
x: 0, y: -VisibleRegionViewController.overlayHeight, width: 0,
height: VisibleRegionViewController.overlayHeight)
overlay.frame = overlayFrame
overlay.autoresizingMask = [.flexibleTopMargin, .flexibleWidth]
view.addSubview(overlay)
}
@objc func didTapToggleOverlay() {
let padding = mapView.padding
UIView.animate(withDuration: 2) { [unowned self] in
let size = self.view.bounds.size
if padding.bottom == 0 {
self.overlay.frame = CGRect(
x: 0, y: size.height - VisibleRegionViewController.overlayHeight, width: size.width,
height: VisibleRegionViewController.overlayHeight)
self.mapView.padding = UIEdgeInsets(
top: 0, left: 0, bottom: VisibleRegionViewController.overlayHeight, right: 0)
} else {
self.overlay.frame = CGRect(
x: 0, y: self.mapView.bounds.size.height, width: size.width, height: 0)
self.mapView.padding = .zero
}
}
}
}

View File

@@ -0,0 +1,38 @@
// Copyright 2022 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(
_ scene: UIScene, willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions
) {
guard let scene = scene as? UIWindowScene else { return }
window = .init(windowScene: scene)
let sampleListViewController = SampleListViewController()
let navigationController = UINavigationController(rootViewController: sampleListViewController)
let detailController = UIViewController()
let splitViewController = UISplitViewController()
splitViewController.delegate = sampleListViewController
splitViewController.preferredDisplayMode = .oneBesideSecondary
splitViewController.viewControllers = [navigationController, detailController]
window?.rootViewController = splitViewController
window?.makeKeyAndVisible()
}
}