-
-
Save nazmulkp/74a2a08cc08f0c51972c3aed51c4db19 to your computer and use it in GitHub Desktop.
The following viewDidLoad will (1) set two locations, (2) remove all the previous annotations, and (3) call user defined helper functions (to get route points and draw the route). | |
var loc1: CLLocationCoordinate2D | |
loc1.latitude = 29.0167 | |
loc1.longitude = 77.3833 | |
var origin = Annotation(title: "loc1", subTitle: "Home1", andCoordinate: loc1) | |
objMapView.addAnnotation(origin) | |
// Destination Location. | |
var loc2: CLLocationCoordinate2D | |
loc2.latitude = 19.076000 | |
loc2.longitude = 72.877670 | |
var destination = Annotation(title: "loc2", subTitle: "Home2", andCoordinate: loc2) | |
objMapView.addAnnotation(destination) | |
if arrRoutePoints { | |
// Remove all annotations | |
objMapView.removeAnnotations(objMapView.annotations()) | |
} | |
arrRoutePoints = self.getRoutePoint(from: origin, to: destination) | |
self.drawRoute() | |
self.centerMap() |
The following code will center align the map.
func centerMap() {
var region: MKCoordinateRegion
var maxLat = -90
var maxLon = -180
var minLat = 90
var minLon = 180
for idx in 0..<arrRoutePoints.count {
var currentLocation = arrRoutePoints[idx]
if currentLocation.coordinate.latitude > maxLat {
maxLat = currentLocation.coordinate.latitude
}
if currentLocation.coordinate.latitude < minLat {
minLat = currentLocation.coordinate.latitude
}
if currentLocation.coordinate.longitude > maxLon {
maxLon = currentLocation.coordinate.longitude
}
if currentLocation.coordinate.longitude < minLon {
minLon = currentLocation.coordinate.longitude
}
}
region.center.latitude = (maxLat + minLat) / 2
region.center.longitude = (maxLon + minLon) / 2
region.span.latitudeDelta = maxLat - minLat
region.span.longitudeDelta = maxLon - minLon
objMapView.setRegion(region, animated: true)
}
This function will draw a route and will add an overlay.
func drawRoute() {
var numPoints = arrRoutePoints.count
if numPoints > 1 {
var coords = malloc(numPoints * sizeof(CLLocationCoordinate2D))
for i in 0..<numPoints {
var current = arrRoutePoints[i]
coords[i] = current.coordinate
}
self.objPolyline = MKPolyline(coordinates: coords, count: numPoints)
free(coords)
objMapView.addOverlay(objPolyline)
objMapView.setNeedsDisplay()
}
}