Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@prathap2626 prathap2626 commented Dec 12, 2018

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

@Naveed0

This comment has been minimized.

Copy link

@Naveed0 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