Manage bookmarks

View on GitHub

Access and create bookmarks on a map.

Image of manage bookmarks 1 Image of manage bookmarks 2

Use case

Bookmarks are used for easily storing and accessing saved locations on the map. Bookmarks are of interest in educational apps (e.g. touring historical sites) or more specifically, for a land management company wishing to visually monitor flood levels over time at a particular location. These locations can be saved as bookmarks and revisited easily each time their basemap data has been updated (e.g. working with up to date satellite imagery to monitor water levels).

How to use the sample

The map in the sample comes pre-populated with a set of bookmarks. To access a bookmark and move to that location, tap on a bookmark's name from the list. To add a bookmark, pan and/or zoom to a new location and tap on the "+" button. Enter a unique name for the bookmark and tap "Save", and the bookmark will be added to the list

How it works

  1. Instantiate a new Map.
  2. To create a new bookmark and add it to the bookmark list:
    • Instantiate a new Bookmark object passing in text (the name of the bookmark) and a Viewpoint as parameters.
    • Add the new bookmark to the map with addBookmark(_:).

Relevant API

  • Bookmark
  • Viewpoint

Tags

bookmark, extent, location, zoom

Sample Code

ManageBookmarksView.swift
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Copyright 2024 Esri
//
// 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
//
//   https://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 ArcGIS
import SwiftUI

struct ManageBookmarksView: View {
    /// A map with an imagery basemap and a list of bookmarks.
    @State private var map: Map = {
        // Create a map with a basemap.
        let map = Map(basemapStyle: .arcGISImagery)

        // Add a list of bookmarks to the map.
        let defaultBookmarks = [
            Bookmark(
                name: "Grand Prismatic Spring",
                viewpoint: Viewpoint(latitude: 44.525, longitude: -110.838, scale: 6e3)
            ),
            Bookmark(
                name: "Guitar-Shaped Forest",
                viewpoint: Viewpoint(latitude: -33.867, longitude: -63.985, scale: 4e4)
            ),
            Bookmark(
                name: "Mysterious Desert Pattern",
                viewpoint: Viewpoint(latitude: 27.380, longitude: 33.632, scale: 6e3)
            ),
            Bookmark(
                name: "Strange Symbol",
                viewpoint: Viewpoint(latitude: 37.401, longitude: -116.867, scale: 6e3)
            )
        ]
        map.addBookmarks(defaultBookmarks)

        return map
    }()

    /// The current viewpoint of the map view.
    @State private var viewpoint: Viewpoint?

    /// A Boolean value indicating whether the bookmarks sheet is presented.
    @State private var bookmarksSheetIsPresented = false

    /// A Boolean value indicating whether the new bookmark alert is showing.
    @State private var newBookmarkAlertIsPresented = false

    /// The error shown in the error alert.
    @State private var error: Error?

    var body: some View {
        MapViewReader { mapViewProxy in
            MapView(map: map, viewpoint: viewpoint)
                .onViewpointChanged(kind: .centerAndScale) { viewpoint = $0 }
                .toolbar {
                    ToolbarItemGroup(placement: .bottomBar) {
                        Button("Add Bookmark", systemImage: "plus") {
                            newBookmarkAlertIsPresented = true
                        }

                        Spacer()

                        Button("Bookmarks", systemImage: "book") {
                            bookmarksSheetIsPresented = true
                        }
                        .popover(isPresented: $bookmarksSheetIsPresented) {
                            BookmarksList(map: map) { bookmark in
                                do {
                                    try await mapViewProxy.setBookmark(bookmark)
                                } catch {
                                    self.error = error
                                }
                            }
                            .presentationDetents([.fraction(0.5)])
                            .frame(idealWidth: 320, idealHeight: 380)
                        }
                    }
                }
                .task {
                    // Zoom to the map's first bookmark when the view appears.
                    do {
                        guard let initialBookmark = map.bookmarks.first else { return }
                        try await mapViewProxy.setBookmark(initialBookmark)
                    } catch {
                        self.error = error
                    }
                }
        }
        .newBookmarkAlert(isPresented: $newBookmarkAlertIsPresented) { name in
            // Create a new bookmark and add it to the map.
            guard !name.isEmpty else { return }
            let newBookmark = Bookmark(name: name, viewpoint: viewpoint)
            map.addBookmark(newBookmark)
        }
        .errorAlert(presentingError: $error)
    }
}

private extension ManageBookmarksView {
    /// A list of the bookmarks for a given map.
    struct BookmarksList: View {
        /// The map to get the bookmarks from.
        let map: Map

        /// The action to perform when a list row is tapped.
        let action: (Bookmark) async -> Void

        /// The action to dismiss the view.
        @Environment(\.dismiss) private var dismiss: DismissAction

        /// The list of the map's bookmarks.
        @State private var bookmarks: [Bookmark] = []

        var body: some View {
            NavigationStack {
                List {
                    ForEach(bookmarks, id: \.self) { bookmark in
                        Button {
                            dismiss()
                            Task {
                                await action(bookmark)
                            }
                        } label: {
                            HStack {
                                Text(bookmark.name)
                                Spacer()
                            }
                            .contentShape(Rectangle())
                        }
                    }
                    .onMove { fromOffsets, toOffset in
                        // Reorder the bookmarks on row move.
                        bookmarks.move(fromOffsets: fromOffsets, toOffset: toOffset)
                        map.removeAllBookmarks()
                        map.addBookmarks(bookmarks)
                    }
                    .onDelete { offsets in
                        // Delete the bookmarks at the given offsets on row deletion.
                        let bookmarksToRemove = offsets.map { bookmarks[$0] }
                        map.removeBookmarks(bookmarksToRemove)
                        bookmarks.remove(atOffsets: offsets)
                    }
                    .buttonStyle(.plain)
                }
                .navigationTitle("Bookmarks")
                .navigationBarTitleDisplayMode(.inline)
                .toolbar {
                    ToolbarItem(placement: .topBarLeading) {
                        // Note: There is a bug in iOS 17 that prevents the `EditButton` from working
                        // on the first tap when it is embedded in a `NavigationStack` in a `popover`.
                        EditButton()
                    }
                    ToolbarItem(placement: .confirmationAction) {
                        Button("Done") {
                            dismiss()
                        }
                    }
                }
            }
            .onAppear {
                bookmarks = map.bookmarks
            }
        }
    }

    /// An alert that allows the user to enter a name for a new bookmark.
    struct NewBookmarkAlert: ViewModifier {
        /// A binding to a Boolean value that determines whether to present the alert.
        @Binding var isPresented: Bool

        /// The action to perform when the save button is pressed.
        let onSave: (String) -> Void

        /// The name for the new bookmark in the text field.
        @State private var newBookmarkName = ""

        func body(content: Content) -> some View {
            content
                .alert(
                    "Add bookmark",
                    isPresented: $isPresented,
                    actions: {
                        TextField("Name", text: $newBookmarkName)

                        Button("Cancel", role: .cancel) {
                            newBookmarkName.removeAll()
                        }

                        Button("Save") {
                            onSave(newBookmarkName)
                            newBookmarkName.removeAll()
                        }
                    }
                )
        }
    }
}

private extension View {
    /// Presents an alert to add a new bookmark.
    /// - Parameters:
    ///   - isPresented: A binding to a Boolean value that determines whether to present the alert.
    ///   - onSave: The action to perform when the save button is pressed.
    /// - Returns: A new `View`.
    func newBookmarkAlert(
        isPresented: Binding<Bool>,
        onSave: @escaping (String) -> Void
    ) -> some View {
        modifier(ManageBookmarksView.NewBookmarkAlert(isPresented: isPresented, onSave: onSave))
    }
}

#Preview {
    NavigationStack {
        ManageBookmarksView()
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.