dang dang - 2 months ago 28
iOS Question

Create multiple markers using Google iOS SDK

I am a newbie in Swift. I was ale to get 2 markers on Google Maps:

import UIKit
import GoogleMaps

class ViewController: UIViewController {

// You don't need to modify the default init(nibName:bundle:) method.

override func loadView() {
let camera = GMSCameraPosition.cameraWithLatitude(37.0902, longitude: -95.7129, zoom: 3.0)
let mapView = GMSMapView.mapWithFrame(CGRect.zero, camera: camera)
mapView.myLocationEnabled = true
view = mapView

let state_marker = GMSMarker()
state_marker.position = CLLocationCoordinate2D(latitude: 61.370716, longitude: -152.404419)
state_marker.title = "Alaska"
state_marker.snippet = "Hey, this is Alaska"
state_marker.map = mapView

let state_marker1 = GMSMarker()
state_marker1.position = CLLocationCoordinate2D(latitude: 32.806671, longitude: -86.791130)
state_marker1.title = "Alabama"
state_marker1.snippet = "Hey, this is Alabama"
state_marker1.map = mapView

}
}


I need to add 51 more markers to different latitude and longitude for each state with different title and snippet.

I can probably just copy this block 51 times but is there a way to optimize this code?

Answer

You should create a struct like this:

struct State {
    let name: String
    let long: CLLocationDegrees
    let lat: CLLocationDegrees
}

Then create an array of this struct in your VC:

let states = [
    State(name: "Alaska", long: -152.404419, lat: 61.370716),
    State(name: "Alabama", long: -86.791130, lat: 32.806671),
    // the other 51 states here...
]

Now you can just loop through the array, adding markers in each iteration:

for state in states {
    let state_marker = GMSMarker()
    state_marker.position = CLLocationCoordinate2D(latitude: state.lat, longitude: state.long)
    state_marker.title = state.name
    state_marker.snippet = "Hey, this is \(state.name)"
    state_marker.map = mapView
}

You might also want to add a dictionary that stores the names of the states as keys and the corresponding GMSMarker as value. This way, you can modify the markers later.

var markerDict: [String: GMSMarker] = [:]

override func loadView() {

    for state in states {
        let state_marker = GMSMarker()
        state_marker.position = CLLocationCoordinate2D(latitude: state.lat, longitude: state.long)
        state_marker.title = state.name
        state_marker.snippet = "Hey, this is \(state.name)"
        state_marker.map = mapView
        markerDict[state.name] = state_marker
    }

}
Comments