对于系统的地图我们使用的可能不是很多,然而,系统的地图功能也很强大,尤其是iOS11以后,加上了点得聚合功能,这是地图开发更加有力。更疯狂,而且不需要自己计算合并逻辑,系统会自动计算。大大开放开了开发者的开发空间,提高了开发效率,有点不足之处就是11以后才能使用。对于尝鲜的开发者来说也很不错,现在都等iOS13了估计11一下的很少,所以完全可以适配了。
设备: xcode 10.1 语言: swift 4.2 系统要求11以上。
重点来了,先来看个效果图:
效果图看着很棒我们来实现他吧。
我们用的是swift,我们先导入MapKit框架。然后创建mapview
cahMap = MKMapView(frame: view.bounds);
cahMap.delegate = self;
view.addSubview(cahMap);
cahMap.showsUserLocation = true;
cahMap.userTrackingMode = .follow;
cahMap.showsCompass = true;
cahMap.showsTraffic = true;
cahMap.showsBuildings = true;
cahMap.showsScale = true;
cahMap.showsPointsOfInterest = true;
cahMap.register(CahCellView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier);
这里简单的创建了一个地图。我们再配置一个定位功能。
let userTrackingButton = MKUserTrackingButton(mapView: cahMap)
userTrackingButton.layer.backgroundColor =
UIColor.white.withAlphaComponent(0.8).cgColor;
userTrackingButton.layer.borderColor = UIColor.white.cgColor
userTrackingButton.layer.borderWidth = 1
userTrackingButton.layer.cornerRadius = 5
userTrackingButton.isHidden = false
view.addSubview(userTrackingButton)
userTrackingButton.frame = .init(x: view.frame.width - 50, y:
view.frame.height - 60, width: 40, height: 40);
我们需要实现mapview的代理:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) ->
MKAnnotationView? {
if annotation is ChurchModel {
let cell = mapView.dequeueReusableAnnotationView(withIdentifier:
MKMapViewDefaultAnnotationViewReuseIdentifier, for: annotation)
as! CahCellView;
return cell;
}
return nil;
}
这里需要说明一下,这里需要判断是否是自定的大头针,如果不是就返回空,会使用系统默认的样式,我们可以自定义,一般的显示用户的位置是一个原点,所以我们只要放回空既可以使用系统的原点了。
下面是大头针的自定义:
class CahCellView: MKMarkerAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier);
configCell();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configCell() -> Void {
canShowCallout = true;
clusteringIdentifier = "church";
let rightArrow = UIButton(frame: .init(x: 0, y: 0, width: 32, height: 32));
rightArrow.setTitle("❯", for: .normal);
rightArrow.titleLabel?.textAlignment = .center;
rightArrow.titleLabel?.font = UIFont.systemFont(ofSize: 14);
rightArrow.setTitleColor(UIColor.green, for: .normal);
rightCalloutAccessoryView = rightArrow;
glyphImage = UIImage(named: "abc@2x");
displayPriority = .defaultLow;
markerTintColor = UIColor(displayP3Red: 0.5, green: 0.8, blue: 0.9, alpha: 1);
}
}
自定义大头针需要注意:只有继承 MKMarkerAnnotationView才能具有聚合功能,并且需要我们设置 clusteringIdentifier把相同的类型设置成一个标志,我们这里就一种类型,所以可以写死。
然后运行项目效果就出来了,非常棒的。