Created
December 4, 2014 11:58
-
-
Save milancermak/e0b959a5195d28133a1f to your computer and use it in GitHub Desktop.
Drawing a dashed line on GoogleMaps for iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)drawDashedLineOnMapBetweenOrigin:(CLLocation *)originLocation destination:(CLLocation *)destinationLocation { | |
[self.mapView clear]; | |
CGFloat distance = [originLocation distanceFromLocation:destinationLocation]; | |
if (distance < kMinimalDistance) return; | |
// works for segmentLength 22 at zoom level 16; to have different length, | |
// calculate the new lengthFactor as 1/(24^2 * newLength) | |
CGFloat lengthFactor = 2.7093020352450285e-09; | |
CGFloat zoomFactor = pow(2, self.mapView.camera.zoom + 8); | |
CGFloat segmentLength = 1.f / (lengthFactor * zoomFactor); | |
CGFloat dashes = floor(distance / segmentLength); | |
CGFloat dashLatitudeStep = (destinationLocation.coordinate.latitude - originLocation.coordinate.latitude) / dashes; | |
CGFloat dashLongitudeStep = (destinationLocation.coordinate.longitude - originLocation.coordinate.longitude) / dashes; | |
CLLocationCoordinate2D (^offsetCoord)(CLLocationCoordinate2D coord, CGFloat latOffset, CGFloat lngOffset) = | |
^CLLocationCoordinate2D(CLLocationCoordinate2D coord, CGFloat latOffset, CGFloat lngOffset) { | |
return (CLLocationCoordinate2D) { .latitude = coord.latitude + latOffset, | |
.longitude = coord.longitude + lngOffset }; | |
}; | |
GMSMutablePath *path = GMSMutablePath.path; | |
NSMutableArray *spans = NSMutableArray.array; | |
CLLocation *currentLocation = originLocation; | |
[path addCoordinate:currentLocation.coordinate]; | |
while ([currentLocation distanceFromLocation:destinationLocation] > segmentLength) { | |
CLLocationCoordinate2D dashEnd = offsetCoord(currentLocation.coordinate, dashLatitudeStep, dashLongitudeStep); | |
[path addCoordinate:dashEnd]; | |
[spans addObject:[GMSStyleSpan spanWithColor:UIColor.blueColor]]; | |
CLLocationCoordinate2D newLocationCoord = offsetCoord(dashEnd, dashLatitudeStep / 2.f, dashLongitudeStep / 2.f); | |
[path addCoordinate:newLocationCoord]; | |
[spans addObject:[GMSStyleSpan spanWithColor:UIColor.clearColor]]; | |
currentLocation = [[CLLocation alloc] initWithLatitude:newLocationCoord.latitude | |
longitude:newLocationCoord.longitude]; | |
} | |
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path]; | |
polyline.map = self.mapView; | |
polyline.spans = spans; | |
polyline.strokeWidth = 4; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I tried the above code. this code is not working for me.