Skip to content

Instantly share code, notes, and snippets.

@milancermak
Created December 4, 2014 11:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milancermak/e0b959a5195d28133a1f to your computer and use it in GitHub Desktop.
Save milancermak/e0b959a5195d28133a1f to your computer and use it in GitHub Desktop.
Drawing a dashed line on GoogleMaps for iOS
- (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;
}
@prathap2626
Copy link

Hi,
I tried the above code. this code is not working for me.

@Naveed0
Copy link

Naveed0 commented Dec 30, 2020

Same, it doesn't work anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment