运用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;

//    }

}

Swift之高德地图的调用相关推荐

  1. Swift基础 - - 高德地图实践

    高德地图开发需要自己到官网http://lbs.amap.com/console/ 注册一个ak,新建一个swift工程,然后在Info.plist中添加一个NSLocationAlwaysUsage ...

  2. 高德地图api调用demo_高德地图定位如何调用api?

    我看了下,貌似没有得到具体街道的位置,不过可以得到经纬度相关信息 AMap.Geolocation定位服务插件.基于HTML5的定位接口,只有支持该定位接口的浏览器才能使用该功能.它在浏览器原生定位接 ...

  3. 高德地图API调用和标准(转)

    看过高德地图API的同学都知道,高德地图不同端调用是不一样的,作为一个前端菜鸟,前一阵分别在pc端和移动端分别调用了高德地图.情况是这个样子的,PC端呢我们可以用高德API的web端的javascri ...

  4. ios html调起高德地图,iOS 调用百度地图, 高德地图,苹果自带的地图

    在你项目的info.plist添加 LSApplicationQueriesSchemes 为KEY 类型为NSArray;添加对应的白名单 高德:iosamap百度:baidumap - (void ...

  5. 高德地图api调用demo_一 (1)高德SDK的使用

    1 申请高德SDK 需要填写SHA1安全码&包名 文档解决方案 https://lbs.amap.com/faq/top/hot-questions/249 package name 获取bu ...

  6. [Python 高德地图] API调用学习历程(四)

    [四]高德天气API调用 通过调用天气,应用在QQ机器人上,实现查天气功能 Python代码示例: async def get_weather_of_city(city: str) -> str ...

  7. 高德地图api调用demo_微信小程序----高德地图API实现的DEMO

    [实例简介] 微信小程序----高德地图API实现的周边,天气,路线规划,地址详情等的DEMO.简单的效果,问一下官方能不能不要乱涨积分,你们涨积分,作者被骂!我真的很失望,再这样,我就不上传资源了! ...

  8. python高德地图api调用实例_Python 利用高德地图api实现经纬度与地址的批量转换...

    我们都知道,可以使用高德地图api实现经纬度与地址的转换.那么,当我们有很多个地址与经纬度,需要批量转换的时候,应该怎么办呢? 在这里,选用高德Web服务的API,其中的地址/逆地址编码,可以实现经纬 ...

  9. swift 中高德地图随时读取坐标地点的写法

    自己写的方法  不比比  自己能看懂就行   只用作自己学习swift的总结 import UIKit typealias block = (String,String) ->() class ...

最新文章

  1. 自定义服务器怎么调98k,《刺激战场》如何开自定义房间?升级可领房卡,3倍物资98k随便捡...
  2. [深度学习]知识蒸馏技术
  3. CentOS7.2中安装rabbitmq
  4. 超简单的memcached集群搭建
  5. BZOJ5215[Lydsy2017省队十连测] 商店购物
  6. easydarwin ffmpeg
  7. 家用无线网络优化方案
  8. 文本分类数据和评价指标
  9. 使用matlab导入excel表格带有时间的数据并绘制曲线
  10. 适当的资本运作能有效提高运营商对产业链的掌控力
  11. 亲测有效!解决文件名过长无法删除的情况
  12. 不用函数,教你快速查找两张表格中的重复内容。
  13. RTSP播放器网页web无插件直播流媒体音视频播放器EasyPlayer-RTSP-Android解码获取视频帧的方法
  14. C Runtime Library 与 STL
  15. 智能车浅谈——控制规律篇
  16. C++ time.h 库详解
  17. 虚拟化系统到VMware虚拟机
  18. JAVA工具【八】RmbUtils 人民币大小写转换工具
  19. 蝉知门户系统迁移到SAE平台-对蝉知2.5版本部分功能的限制
  20. AS调用百度地图定位

热门文章

  1. 八数码问题中的逆序数
  2. 外点罚函数法的MATLAB实现,一、非线性规划问题的几种求解方法1罚函数法(外点法).ppt...
  3. 分享180个美美的CSS渐变样式效果图
  4. 【PMP】成本的分类
  5. 助力中小企业级连云端,促进工业互联网平台蓬勃发展,全套解决方案。附:技术产品...
  6. 大数据应用的几个典型例子
  7. onShow onHide页面生命周期不执行
  8. [转载]大数据量,海量数据 处理方法总结 作者phylips@bmy
  9. [music]Brand new day--Ryan Star
  10. 推荐一个免费的刷题网站