2015/02/13

Swfit IOS add marker on the Google Maps

Code:
//
//  ViewController.swift
//  Sample
//
//  Created by C.Y.Fang on 2/10/15.
//  Copyright (c) 2015 C.Y.Fang. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    let url = "http://data.kaohsiung.gov.tw/Opendata/DownLoad.aspx?Type=2&CaseNo1=AU&CaseNo2=1&FileType=2&Lang=C&FolderType=O"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        var camera = GMSCameraPosition.cameraWithLatitude(22.60583276,
            longitude: 120.307702,  zoom: 10)
        var mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        self.view = mapView
        let json:AnyObject! = getJsonFromURL(url)
        drawMaker(mapView, json: json)
    }

    private func getJsonFromURL(url:String)->AnyObject?{
        let url = NSURL(string: url)
        let data = NSData(contentsOfURL: url!)
        return NSJSONSerialization.JSONObjectWithData(data!,
            options: NSJSONReadingOptions.AllowFragments, error: nil)
    }
    
    private func drawMaker(mapView:GMSMapView, json:AnyObject?){
        if let array = json as? NSArray {
            for temp in array{
                let name = temp["車站中文名稱"] as NSString!
                let lat = (temp["車站緯度"] as NSString!).doubleValue
                let lng = (temp["車站經度"] as NSString!).doubleValue
                
                var market = GMSMarker()
                market.position =  CLLocationCoordinate2DMake(lat ,lng)
                market.title = name
                market.map = mapView
            }
        }
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}

執行結果: