Swift之高德地图的调用

运用swift开发已有半年之久,最近闲来没事。学习了一点地图的知识,现在来与大家分享。直接上代码吧!

 《一》高德地图搜索功能

控制器

//

//  ViewController.swift

//  AmapSeach

//

//  Created by yanfa-fengchuang on 16/8/15.

//  Copyright © 2016 yanfa-fengchuang. All rights reserved.

//


import UIKit


class ViewController: UIViewController,AMapSearchDelegate,AMapLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource{

    

    var search:AMapSearchAPI!

    let locationManager = AMapLocationManager()

    var currentCity:String!

    var currentCityBtn:UIButton!

    var searchTF:UITextField!

    var location:CLLocation!

    var cancleBtn:UIButton!

    var CirtyArray:NSArray!

    var addressTableview:UITableView!

    var number:String!

    var poi :AMapPOI?

    var dataArray:NSMutableArray!

    var keyWord:String!

    var citiTableview:UITableView!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor.colorWithHex("#F6F6F6")!

        

        self.dataArray = NSMutableArray()

        //MARK:单次定位获取当前城市

        setHeardview()

        setOnceLocation()

        CirtyArray = ["江阴市","新沂市","邳州市","溧阳市","金坛市","常熟市","张家港市","昆山市","吴江市","太仓市","启东市","如皋市","通州市","海门市","东台市","大丰市","仪征市","高邮市","江都市","丹阳市","扬中市","句容市","兴化市","靖江市","泰兴市","姜堰市"]

        self.number = "0"

        setTableview()

        setCityTableview()

        

        search = AMapSearchAPI()

        search.delegate = self

        

    }

    

    //MARK:自定义一个假的导航条

    func setHeardview(){

        //MARK:最底下的view

        let heardview = UIView()

        heardview.frame = CGRectMake(0, 0, self.view.frame.size.width, 64)

        heardview.layer.borderWidth = 1

        heardview.layer.borderColor = UIColor.colorWithHex("#E0E0E0")!.CGColor

        self.view.addSubview(heardview)

        

        //MARK:选择城市的按钮

        self.currentCityBtn = UIButton()

        self.currentCityBtn.setTitle("北京市", forState: .Normal)

        self.currentCityBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)

        self.currentCityBtn.titleLabel?.font = UIFont.systemFontOfSize(15)

        self.currentCityBtn.frame = CGRectMake(5, 25, 60, 30)

        self.currentCityBtn.addTarget(self, action: #selector(ViewController.currentCityBtnAction), forControlEvents: .TouchUpInside)

        heardview.addSubview(currentCityBtn)

        

        //MARK:竖线

        let label = UILabel()

        label.frame = CGRectMake(75, 25, 1, 30)

        label.backgroundColor = UIColor.colorWithHex("#E0E0E0")!

        heardview.addSubview(label)

        

        //MARK: 搜索框

        self.searchTF = UITextField()

        self.searchTF.frame = CGRectMake(85, 25, 180, 30)

        self.searchTF.placeholder = "您要去哪"

        self.searchTF.font = UIFont.systemFontOfSize(15)

        heardview.addSubview(self.searchTF)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.beginSearch), name: UITextFieldTextDidChangeNotification, object: nil)

        //MARK:取消按钮

        self.cancleBtn = UIButton()

        self.cancleBtn.setTitle("取消", forState: .Normal)

        self.cancleBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)

        self.cancleBtn.titleLabel?.font = UIFont.systemFontOfSize(15)

        self.cancleBtn.frame = CGRectMake(270, 25, 40, 30)

        heardview.addSubview(cancleBtn)

    }

    

    //MARK:城市的tableview

    func setCityTableview(){

        self.citiTableview = UITableView()

        self.citiTableview.frame = CGRectMake(0, 64, self.view.bounds.size.width, self.view.frame.size.height-64)

        self.citiTableview.delegate = self

        self.citiTableview.dataSource = self

        self.citiTableview.tableFooterView = UIView(frame:CGRectZero)

        self.view.addSubview(self.citiTableview)

        self.citiTableview.hidden = true

        //        self.citiTableview.registerClass(UITableViewCell.self, forCellReuseIdentifier: "CELLID")

    }

    

    //MARK:地点的tableview

    func setTableview(){

        self.addressTableview = UITableView()

        self.addressTableview.frame = CGRectMake(0, 64, self.view.bounds.size.width, self.view.frame.size.height-64)

        self.addressTableview.delegate = self

        self.addressTableview.dataSource = self

        self.addressTableview.tableFooterView = UIView(frame:CGRectZero)

        self.view.addSubview(self.addressTableview)

        self.addressTableview.hidden = true

    }

    

    

    //MARK:当前城市按钮的点击事件

    func currentCityBtnAction(){

        self.number = "1"

        self.addressTableview.hidden = true

        self.citiTableview.hidden = false

        self.citiTableview.reloadData()


    }

    

    

    //*****************************************************   获取当前城市    ***********************************************

    //MARK:单次定位获取当前城市

    func setOnceLocation(){

        //精度

        self.locationManager.desiredAccuracy = 100

        //   定位超时时间,最低2s,此处设置为11s

        self.locationManager.locationTimeout = 11

        //   逆地理请求超时时间,最低2s,此处设置为12s

        self.locationManager.reGeocodeTimeout = 12

        self.locationManager.delegate = self

        self.locationManager.requestLocationWithReGeocode(true) { (location, regeocode, error) in

            if (error == nil){

                self.currentCityBtn.setTitle(regeocode.city, forState: .Normal)

                self.location = location

                self.keyWord = regeocode.city

                print(location.coordinate.longitude ?? 0.00)

                print(location.coordinate.latitude ?? 0.00)

                //MARK:根据关键词搜索周边地理位置信息

                self.setSearch()

            }

        }

    }

    

    //MARK:根据关键词搜索周边地理位置信息

    func setSearch(){

        

        let request = AMapPOIAroundSearchRequest()

        request.location = AMapGeoPoint.locationWithLatitude(CGFloat(self.location.coordinate.latitude), longitude: CGFloat(self.location.coordinate.longitude))

        request.keywords = self.keyWord

        request.sortrule = 0

        request.requireExtension = true

        search.AMapPOIAroundSearch(request)

    }

    

    //MARK: 返回周边位置信息(地点 ,经度,维度,附近一些商家的名字)

    func onPOISearchDone(request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {

        if response.pois.count == 0 {

            return

        }

        

        for p:AMapPOI in response.pois {

            self.dataArray.addObject(p)

        }

        self.addressTableview.hidden = false

        self.addressTableview.reloadData()

        self.addressTableview.registerClass(PointCell.self, forCellReuseIdentifier: "CELL")

    }

    

    //************************************   tableview   的代理方法   ************************************

    

    //MARK:tableview 的代理方法

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if self.number != "0" {

            return self.CirtyArray.count

        }else{

            return self.dataArray.count

        }

    }

    

    //MARK:tableview所显示的内容

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if self.number != "0" {

            let identifier="identtifier";

            var cell=tableView.dequeueReusableCellWithIdentifier(identifier);

            if(cell == nil){

                cell=UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier);

            }

            cell?.textLabel?.text = self.CirtyArray[indexPath.row] as? String

            self.dataArray = NSMutableArray()

            return cell!

            

        }else{

            

            let cell:PointCell = (tableView.dequeueReusableCellWithIdentifier("CELL") as? PointCell)!

            cell.poi = self.dataArray[indexPath.row] as? AMapPOI

            return cell

        }

    }

    

    

    //MARK:CELL的点击事件

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if self.number != "0" {

            self.number = "0"

            self.currentCityBtn.setTitle(self.CirtyArray[indexPath.row] as? String, forState: .Normal)

            self.citiTableview.hidden = true

            self.searchTF.text = currentCityBtn.titleLabel?.text

           beginSearch()

//            self.addressTableview.reloadData()

            

        }else{

            self.searchTF.text = ((self.dataArray[indexPath.row] as? AMapPOI)!).name

            print(((self.dataArray[indexPath.row] as? AMapPOI)!).location)

        }

    }

    

    //MARK: Cell 返回的高度

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        if self.number != "0" {

            return 44

        }else{

            return 55

        }

    }

    

    //****************************************************   根据输入的关键字搜索   *****************************

    

    //MARK: 开始搜索

    func beginSearch() {

        self.dataArray.removeAllObjects()

        let keywordsRequest = AMapPOIKeywordsSearchRequest()

        keywordsRequest.keywords = searchTF.text!

        keywordsRequest.city = currentCityBtn.titleLabel?.text

        keywordsRequest.requireExtension = true

        print(searchTF.text!)

        search.AMapPOIKeywordsSearch(keywordsRequest)

    }

    

    

}

自定义cell

//

//  PointCell.swift

//  AmapSeach

//

//  Created by yanfa-fengchuang on 16/8/16.

//  Copyright © 2016 yanfa-fengchuang. All rights reserved.

//


import UIKit


class PointCell: UITableViewCell {


    

   var pointLabel: UILabel!

   var addressLabel: UILabel!

   var poi :AMapPOI?{

        didSet{

            pointLabel.text = poi?.name

            addressLabel.text = poi?.address

        }

    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)

        install()

    }

    

    func  install(){

        self.pointLabel = UILabel()

        self.pointLabel.frame = CGRectMake(10, 2.5, screenWidth, 25)

        self.pointLabel.font = UIFont.systemFontOfSize(16)

        self.pointLabel.textColor = UIColor.blackColor()

        self.addSubview(self.pointLabel)

        

        

        

        self.addressLabel = UILabel()

        self.addressLabel.frame = CGRectMake(10, 25, screenWidth, 25)

        self.addressLabel.font = UIFont.systemFontOfSize(14)

        self.addressLabel.textColor = UIColor.orangeColor()

        self.addSubview(self.addressLabel)

    }

    

    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }


}

《二》高德地图地图几个简单的功能

//

//  ViewController.swift

//  CustomPin

//

//  Created by yanfa-fengchuang on 16/8/15.

//  Copyright © 2016 yanfa-fengchuang. All rights reserved.

//

 /// 注意  再使用地图的时候一定要开启定位服务   不然  你根本就不能显示你当前的位置所以一定要在plist文件里面添加  NSLocationAlwaysUsageDescription    请允许获取位置信息)允许定位的功能


import UIKit


let screenHight = UIScreen.mainScreen().bounds.size.height

let screenWidth = UIScreen.mainScreen().bounds.size.width


class ViewController: UIViewController,MAMapViewDelegate {


    var mapView: MAMapView!

    

    var location: CLLocationCoordinate2D!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

//*****************************************************

    

        //地图简单的一些属性

        initMapView()

        

//*****************************************************

        //进入地图显示给定的位置

        //showCustomPoint()

        

    }

    

    

//**************************************************************************

  

    //MARK: 设置地图

    func initMapView() {

        mapView = MAMapView(frame: self.view.bounds)

        mapView.delegate = self

        

        //MARK:是否显示罗盘

        mapView.showsCompass = false

        

        //MARK:是否显示比例尺

        mapView.showsScale = false

        

        //MARK:是否显示用户位置(小圆点)

        mapView.showsUserLocation = true

        

        //MARK:是否显示用户位置(小圆点跟随用户的位置而移动)

        mapView.userTrackingMode = MAUserTrackingMode.Follow

        

        //MARK:地图精度(就是地图的放大级别)

        mapView.setZoomLevel(15, animated: true)

        view.insertSubview(mapView, atIndex: 0)

        

        let backlocationBtn = UIButton()

        backlocationBtn.frame = CGRectMake(20, screenHight-60, 40, 30)

        backlocationBtn.backgroundColor = UIColor.orangeColor()

        mapView.addSubview(backlocationBtn)

        backlocationBtn.addTarget(self, action: #selector(ViewController.backBtnaction), forControlEvents: .TouchUpInside)

        

        

    }

    

    //MARK: 一键返回用户当前位置按钮的点击事件

    func backBtnaction(){

        //MARK:是否显示用户位置(小圆点跟随用户的位置而移动)

        UIView.animateWithDuration(0.5, animations: { () -> Void in

            self.mapView.userTrackingMode = MAUserTrackingMode.Follow

        }) { (finished) -> Void in

        }


    }

    

 //************************* 给定一个坐标使进入地图的时候就显示这个点****************************

    

    //MARK: 进入地图显示给定的地点的位置 利用系统自带的大头针给添加进去并且显示标注

    func showCustomPoint(){

        mapView = MAMapView(frame: self.view.bounds)

        mapView.delegate = self


        //MARK:地图精度(就是地图的放大级别)

        mapView.setZoomLevel(15, animated: true)

        view.insertSubview(mapView, atIndex: 0)

        

         location = CLLocationCoordinate2D.init(latitude: 31.329674, longitude: 120.610733)

        

        self.mapView.centerCoordinate = location

        let pointAnnotation = MAPointAnnotation()//这个是标注不是大头针

        pointAnnotation.coordinate = location

        pointAnnotation.title = "苏州站"

        pointAnnotation.subtitle = "苏州火车站1号出口"

        mapView.addAnnotation(pointAnnotation)

        mapView.selectAnnotation(pointAnnotation, animated: true)

    }

    

//    //如果没有这一句的话就不会显示标注

//    func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! {

//            let pointReuseIndetifier = "pointReuseIndetifier"

//            var  annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(pointReuseIndetifier)

//            if annotationView == nil {

//                annotationView = MAPinAnnotationView.init(annotation: annotation, reuseIdentifier: pointReuseIndetifier)

//            }

//            annotationView.canShowCallout = true       //设置气泡可以弹出,默认为NO

//            annotationView.draggable = true      //设置标注可以拖动,默认为NO

//            return annotationView;

//    }

    

    

    

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值