Search code examples
iosswiftgoogle-mapsgoogle-polyline

How do I show a polyline that only connects 2 points?


I am using the iOS Google Maps API to show a map. I want to add a line at a particular longitude so that users can know where that longitude is.

This is what I have tried:

let path = GMSMutablePath()
path.add(CLLocationCoordinate2D(latitude: -90, longitude: -122))
path.add(CLLocationCoordinate2D(latitude: 90, longitude: -122))
polyline = GMSPolyline(path: path)
polyline.geodesic = true
polyline.strokeColor = .red
polyline.strokeWidth = 20 // I have set this to a big number to guarantee that my poor eyesight can see the line
polyline.map = mapView

I cannot see the line anywhere!

As a control experiment, I copied the code that drew a rectangle from a tutorial and pasted it just after the above code:

let rect = GMSMutablePath()
rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))

// Create the polygon, and assign it to the map.
let polygon = GMSPolygon(path: rect)
polygon.fillColor = UIColor(red: 0.25, green: 0, blue: 0, alpha: 0.2);
polygon.strokeColor = .black
polygon.strokeWidth = 2
polygon.map = mapView

And it shows the rectangle:

enter image description here

Since my code that draws the line is immediately above the code that draws the rectangle, my code should have been executed as well. It should have drawn a line touching the rectangle, extending from the north pole to the south pole. But why is there no such line?


Solution

  • The problem is that your two points aren't just two arbitrary points and there isn't just one shortest line between them.

    Points (90, X) and (-90, X) are the north and south poles no matter the value of X, and there are infinite lines that connect them. I'd suggest adding the point on the equator (0, X) between the other two points.

    I added a point on the equator between the north pole and south pole and now it only drew a line to the equator.

    I can't explain that. Seems like a bug. Try values near the poles such as 89 and -89 or 89.999 and -89.999.