目前APP端能够集成的地图国内的有百度,高德,国外的有谷歌,但如果做国际化,对安卓开发来说就要接入两种地图 (由于天朝的规定,大家都懂得) 但对于苹果地图开发来说 苹果地图就能满足这种需求,话不多说, 代码走起!
1.接入苹果原生地图首先要导入#import <MapKit/MapKit.h> 并且实现MKMapViewDelegate,CLLocationManagerDelegate 代理
1.1 创建地图
- (void)creatMap{
_map = [[MKMapView alloc]initWithFrame:self.bounds];
_map.delegate=self;
_map.userTrackingMode = MKUserTrackingModeFollow;
//显示指南针
_map.showsCompass = YES;
//显示比例尺
_map.showsScale = YES;
//显示交通状况
_map.showsTraffic = YES;
//显示建筑物
_map.showsBuildings = YES;
//显示用户所在的位置
_map.showsUserLocation = YES;
//显示感兴趣的东西
_map.showsPointsOfInterest = YES;
[self addSubview:_map];
_addressLabel = [[UILabel alloc]init];
_addressLabel.bounds=CGRectMake(0,0,200,40);
_addressLabel.backgroundColor = [UIColor blackColor];
_addressLabel.textColor = [UIColor whiteColor];
_addressLabel.center = self.center;
[self addSubview:_addressLabel];
UITextField*keywordSearchButton = [[UITextFieldalloc]init];
keywordSearchButton.backgroundColor= [UIColorlightGrayColor];
keywordSearchButton.frame=CGRectMake(100,64,100,40);
[keywordSearchButtonaddTarget:self action:@selector(keywordSearch:) forControlEvents:UIControlEventEditingChanged];
[selfaddSubview:keywordSearchButton];
UIButton *hotSearchButton = [UIButton buttonWithType:UIButtonTypeCustom];
hotSearchButton.frame=CGRectMake(0,64,100,40);
[hotSearchButtonsetTitle:@"热点搜索"forState:UIControlStateNormal];
[hotSearchButtonaddTarget:self action:@selector(hotSeatch) forControlEvents:UIControlEventTouchUpInside];
[selfaddSubview:hotSearchButton];
_placetab = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, self.frame.size.width, 300)];
_placetab.delegate = self;
_placetab.dataSource = self;
_placetab.hidden = YES;
[self addSubview:_placetab];
_geoCoder= [[CLGeocoderalloc]init];
}
1.2 实现代理
//每次调用,都会把用户的最新位置(userLocation参数)传进来
- (void)mapView:(MKMapView*)mapView didUpdateUserLocation:(MKUserLocation*)userLocation{
}
- (void)mapView:(MKMapView*)mapView regionWillChangeAnimated:(BOOL)animated{
// JKAnnotation *anno = [[JKAnnotation alloc] init];
// anno.title = @"我是一个大头针";
// anno.subtitle = @"我有一个小弟叫小头";
// anno.coordinate = CLLocationCoordinate2DMake(mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude);
// [mapView addAnnotation:anno];
CLLocation *currLocation = [[CLLocation alloc]initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
[_geoCoderreverseGeocodeLocation:currLocationcompletionHandler:^(NSArray*placemarks,NSError*error) {
for(CLPlacemark* placemarkinplacemarks) {
NSDictionary*address = [placemarkaddressDictionary];
_addressLabel.text= [addressobjectForKey:@"Name"];
NSLog(@"%@", [addressobjectForKey:@"Name"]);
}
}];
NSLog(@"------%f",mapView.centerCoordinate.latitude);
}
2.定位功能
如果想单一实现定位功能 系统有一个 CLLocationManager 实现CLLocationManagerDelegate
2.1 开始定位
-(void)startLocation{
if ([CLLocationManager locationServicesEnabled]) {//判断定位操作是否被允许
self.locationManager= [[CLLocationManageralloc]init];
self.locationManager.delegate = self;//遵循代理
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 10.0f;
[_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8以上版本定位需要)
[self.locationManager startUpdatingLocation];//开始定位
}else{//不能定位用户的位置的情况再次进行判断,并给与用户提示
//1.提醒用户检查当前的网络状况
//2.提醒用户打开定位开关
}
}
//实现代理
- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations{
//当前所在城市的坐标值
CLLocation*currLocation = [locationslastObject];
NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude,currLocation.coordinate.longitude,currLocation.altitude);
//根据经纬度反向地理编译出地址信息
CLGeocoder* geoCoder = [[CLGeocoderalloc]init];
[geoCoderreverseGeocodeLocation:currLocationcompletionHandler:^(NSArray*placemarks,NSError*error) {
for(CLPlacemark* placemarkinplacemarks) {
NSDictionary*address = [placemarkaddressDictionary];
// Country(国家) State(省) City(市)
NSLog(@"#####%@",address);
NSLog(@"%@", [addressobjectForKey:@"Country"]);
NSLog(@"%@", [addressobjectForKey:@"State"]);
NSLog(@"%@", [addressobjectForKey:@"City"]);
}
}];
}
-(void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error{
if([errorcode] ==kCLErrorDenied){
//访问被拒绝
}
if ([error code] == kCLErrorLocationUnknown) {
//无法获取位置信息
}
}
3.搜索功能
//关键字搜索
- (void)keywordSearch:(UITextField*)field {
if(field.text.length==0){
_placetab.hidden=YES;
}
//创建地理编码
CLGeocoder*geocoder = [[CLGeocoderalloc]init];
//正向地理编码
[geocodergeocodeAddressString:field.textcompletionHandler:^(NSArray*_Nullableplacemarks,NSError*_Nullableerror) {
if(error ==nil) {
//解析地理位置成功
//成功后遍历数组
for(CLPlacemark*placeinplacemarks) {
//创建大头针
// MyPointAnnotation *annotation = [[MyPointAnnotation alloc] initWithCoorDinate:place.location.coordinate title:place.name subTitle:place.locality information:place.locality];
// //将大头针加入到地图
// [_map addAnnotation:annotation];
[self.dataArrayremoveAllObjects];
[self.dataArrayaddObject:place];
_placetab.hidden=NO;
[_placetabreloadData];
}
}else{
NSLog(@"正向地理编码解析失败");
}
}];
}
//热门搜索
- (void)hotSeatch {
//创建本地搜索请求
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
//设置搜索热点词(自然语言)
request.naturalLanguageQuery = @"学校";
//设置搜索范围,以某个原点为中心,向外扩展一段经纬度距离范围
CLLocationCoordinate2D origionpoint = CLLocationCoordinate2DMake(36.08397, 120.37126);
//设置经纬度跨越范围
MKCoordinateSpan span = MKCoordinateSpanMake(0.3, 0.3);
//设置经纬度搜索区域
MKCoordinateRegionregion =MKCoordinateRegionMake(origionpoint, span);
//将区域赋值给搜索请求对象中的region属性中
request.region= region;
//将地图移动到该区域
[_mapsetRegion:region];
//创建本地搜索对象
MKLocalSearch*search = [[MKLocalSearchalloc]initWithRequest:request];
//开启搜索
[searchstartWithCompletionHandler:^(MKLocalSearchResponse*_Nullableresponse,NSError*_Nullableerror) {
if(error ==nil) {
//搜索成功
//获取搜索结果
NSArray*arrResult = response.mapItems;
for(MKMapItem*iteminarrResult) {
//先取出地图目的坐标对象(标记)
MKPlacemark*placeMark = item.placemark;
/*
96 地标里存放的经纬度,以及位置的地理信息说明,如名字、街道等等
97 */
//创建大头针
JKAnnotation*anno = [[JKAnnotationalloc]init];
anno.title=@"我是一个大头针";
anno.subtitle=@"我有一个小弟叫小头";
anno.coordinate= placeMark.location.coordinate;
[_mapaddAnnotation:anno];
}
}else{
NSLog(@"搜索失败");
}
}];
}
4.自定义大头针 JKAnnotation
.h
#import <Foundation/Foundation.h>
#import<MapKit/MapKit.h>
@interface JKAnnotation : NSObject<MKAnnotation>
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy, nullable) NSString *title;
@property (nonatomic, copy, nullable) NSString *subtitle;
@end
.m
#import "JKAnnotation.h"
@implementation JKAnnotation
@end
// 已经添加了大头针模型,还没有完全渲染出来之前(mapView的代理)
- (void)mapView:(MKMapView*)mapView didAddAnnotationViews:(NSArray *)views{
for(MKAnnotationView*annotationViewinviews) {
//目标位置
CGRecttargetRect = annotationView.frame;
//先让其在最顶上
annotationView.frame=CGRectMake(targetRect.origin.x,0, targetRect.size.width, targetRect.size.height);
//最后通过动画展示到最终的目标地方
[UIView animateWithDuration:0.3 animations:^{
annotationView.frame= targetRect;
}];
}
}//如果不要这种效果这段代码也可以不需要
// 大头针视图的重用,大头针也存在着重用的机制,方便优化内存
// 每次添加大头针都会调用此方法 可以设置大头针的样式
- (MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id)annotation{
// 判断大头针位置是否在原点,如果是则不加大头针或者添加属于自己特殊图标
if([annotationisKindOfClass:[MKUserLocationclass]]) {returnnil; }
//1.定义一个可重用标识符
staticNSString*reuseIdentifier =@"mapView";
MKAnnotationView*annotationView = (MKAnnotationView*)[mapViewdequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
if(annotationView ==nil) {
annotationView = [[MKAnnotationViewalloc]initWithAnnotation:annotationreuseIdentifier:reuseIdentifier];
}
//设置可重用标识符的相关属性
// 显示标题和副标题
annotationView.canShowCallout=YES;
// 设置图片(用户头像,或者商品/超市/汽车/单车等等图片)
annotationView.image= [UIImageimageNamed:@"header_new"];
//须导入#import "UIImageView+WebCache.h"头文件
// [annotationView.image sd_setImageWithURL:[NSURL URLWithString:[dict valueForKey:@"icon"]] placeholderImage:[UIImage imageNamed:@"默认图片"]];
returnannotationView;
// 判断大头针位置是否在原点,如果是则不加大头针
// if([annotation isKindOfClass:[mapView.userLocation class]]){
// return nil;
// }
// //设置自定义大头针
// JKAnnotationView *annotationView = (JKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"otherAnnotationView"];
// if (annotationView == nil) {
// annotationView = [[JKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"otherAnnotationView"];
// }
// annotationView.image = [UIImage imageNamed:@"header_new"];
// return annotationView;
}
demo 地址:https://github.com/XUDAQUAN/AppleMap
网友评论