latitude and longitude points from MKPolyline
To get coordinates of the polyline from an MKRoute
, use the getCoordinates:range:
method.
That method is in the MKMultiPoint
class which MKPolyline
inherits from.
That also means this works for any polyline -- whether it was created by you or by MKDirections
.
You allocate a C array big enough to hold the number of coordinates you want and specify the range (eg. all points starting from the 0th).
Example:
//route is the MKRoute in this example
//but the polyline can be any MKPolyline
NSUInteger pointCount = route.polyline.pointCount;
//allocate a C array to hold this many points/coordinates...
CLLocationCoordinate2D *routeCoordinates
= malloc(pointCount * sizeof(CLLocationCoordinate2D));
//get the coordinates (all of them)...
[route.polyline getCoordinates:routeCoordinates
range:NSMakeRange(0, pointCount)];
//this part just shows how to use the results...
NSLog(@"route pointCount = %d", pointCount);
for (int c=0; c < pointCount; c++)
{
NSLog(@"routeCoordinates[%d] = %f, %f",
c, routeCoordinates[c].latitude, routeCoordinates[c].longitude);
}
//free the memory used by the C array when done with it...
free(routeCoordinates);
Depending on the route, be prepared for hundreds or thousands of coordinates.
MKpolyline not displaying correctly for given coordinates
It was a problem with the data array. since im getting the coordinates from coredata those werent in order. so thats why it didnt draw the perfect line one after another. once i sorted the array i got it perfectly.
locationDetails = locationDetails.sorted(by: { $0.id < $1.id })
Swift, MKPolyline how to create polyline between coordinate point
You're creating multiple polylines with a single point, instead of a single polyline with multiple points. It's hard to get the code right without knowing your dictionary structure, but this should be more in line with what you're trying to do:
var arrayToDraw: Array<Any> = []
var forpolyline: Array<CLLocationDegrees> = []
var forpolyline2: CLLocationCoordinate2D = [CLLocationCoordinate2D]()
func showRoute() {
for h in 0...(orderFinalDictionary.count - 1){
arrayToDraw = orderFinalDictionary[h].value
print(arrayToDraw)
var arrayToDrawCount = arrayToDraw.count
for n in 0...(arrayToDrawCount - 1){
forpolyline = (arrayToDraw[n] as! Array<CLLocationDegrees>)
forpolyline2.append(CLLocationCoordinate2D(latitude: forpolyline[0], longitude: forpolyline[1]))
}
print(forpolyline2)
let geodesic = MKPolyline(coordinates: &forpolyline2, count: forpolyline2.count)
self.mapView.add(geodesic)
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
renderer.strokeColor = UIColor.red
renderer.lineWidth = 3
return renderer
}
How to get valid coodinates from Apple map using MKpolyline object
The route.polyline.points
are map points...
If you wants the coordinates.. you have to "convert" MapPoints to Cooridnates..
for (int c = 0; c < (int)pointCount; c++)
{
// MapPoints
NSLog(@"routeMapPoints = %f, %f",
route.polyline.points[c].x, route.polyline.points[c].y);
// Coordinates
CLLocationCoordinate2D coordinate = MKCoordinateForMapPoint(route.polyline.points[c]);
NSLog(@"routeCoordinates = %f, %f",
coordinate.latitude, coordinate.longitude);
}
I'm trying to draw polyline on coordinates(lat, long) coming from API using swift 3 in map kit but unable to make polyline
I'm sure if you shared the results of the print
statement, the problem would have been obvious. You're probably seeing lots of print statements. Bottom line, you should define your array outside of the for
loop, only append
values within the loop, and then add the polyline after the loop:
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
let data = json["punchdetails"] as? [[String: Any]] {
var annotations = [MKPointAnnotation]()
for datas in data {
let lat = datas["punch_loc_lat"] as! String
let long = datas["punch_loc_long"] as! String
let latitude = CLLocationDegrees(lat)
let longitude = CLLocationDegrees(long)
let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotations.append(annotation)
}
self.TheMap.delegate = self // you really should do this in IB or, if you feel compelled to do it programmatically, in viewDidLoad
// Connect all the mappoints using Poly line.
let points = annotations.map { $0.coordinate }
print("this is points = \(points)")
let polyline = MKPolyline(coordinates: &points, count: points.count)
DispatchQueue.main.async {
self.centerMapOnLocation(location: annotations[0], regionRadius: 2000.0)
self.TheMap.addAnnotations(annotations)
self.TheMap.add(polyline)
}
}
} catch {
print(error)
}
Note, I'd also do all interaction with the map view from the main queue.
MKPolyline only draw points instead of lines
The userLocation
object the map view passes to the didUpdateUserLocation
delegate method is the same object every time.
The coordinate
inside the object may be different at each moment but each call to the delegate method always points to the same container object.
Specifically, it always points to the same object that the map view's userLocation
property points to (mapView.userLocation
). You can see this if you NSLog
userLocation
and mapView.userLocation
and notice their memory addresses are the same each time.
For this reason, when the code does this:
[self.trackPointArray addObject:userLocation];
it just adds the same object reference to the array multiple times.
Later, when the code loops through the trackPointArray
array, each call to [location coordinate]
returns the same coordinate every time because location
always points to the same object (mapView.userLocation
) and the coordinate does not change during the loop.
So each time the delegate method is called, a polyline is created with N coordinates (all the same) which ends up drawing a "dot".
The reason you see multiple dots is because the code is not removing previous overlays.
To fix all this, one easy way is to create a new CLLocation
instance each time you want to add the updated coordinates:
CLLocation *tpLocation = [[CLLocation alloc]
initWithLatitude:userLocation.coordinate.latitude
longitude:userLocation.coordinate.longitude];
[self.trackPointArray addObject:tpLocation];
Additionally, you should remove the previous overlay before adding the updated line. You won't notice the previous lines if you don't do this but they'll be there using up memory and performance:
[self.myMapView removeOverlays:self.myMapView.overlays];
[self.myMapView addOverlay:polyLine];
MKPolyline Intersecting coordinates ios
Try This
CGFloat m1, c1, m2, c2;
CGFloat x11, y11, x12, y12; //line 1
CGFloat x21, y21, x22, y22; //line 2
CGFloat dx, dy;
CGFloat intersection_X, intersection_Y;
dx = x12 - x11;
dy = y12 - y11;
m1 = dy / dx;
c1 = y11 - m1 * x11;
dx = x22 - x21;
dy = y22 - y21;
m2 = dy / dx;
c2 = y22 - m2 * x22;
if( (m1 - m2) == 0)
{
NSLog(@"No Intersection between the lines");
}
else
{
intersection_X = (c2 - c1) / (m1 - m2);
intersection_Y = m1 * intersection_X + c1;
}
Related Topics
Reload Section Without Reloading Section Header
Customizing the Colors of a Uisegmentedcontrol
How to Reset the Application Data After Each Test with Xcode 7 UI Testing
iOS 10 Heading Arrow for Mkuserlocation Dot
Detect Moment When Newline Starts in Uitextview
How to Take Screenshot of Portion of Uiview
Scanning Barcode or Qr Code in Swift 3.0 Using Avfoundation
How to Determine If the Sim/Phone Number Has Changed
Workaround for Rounded Corners of Grouped Uitableview, iOS7
Exception with Insertobject:Atindex: on iOS6
Module 'Alamofire' Has No Member Named 'Request'
Uicontroleventeditingchanged Doesn't Get Fired When Using Settext of Uitextfield
Completely Disable Firebase/Analytics to Stop Console Spam on App Startup
Firinstanceid/Warning Stop!! Will Reset Deviceid from Memory [Xcode:Console Log]