Is there a way to get directions(just routes) using google for mkmapview?

前端 未结 3 1053
既然无缘
既然无缘 2021-01-15 06:53

I\'m using swift on iOS and using MKMapView. I\'ve been working on giving a user a from - to textfield and letting the user have a form of route between the from and to loca

3条回答
  •  深忆病人
    2021-01-15 07:31

    I think this Stackoverflow answer can convert the encoded polyline to MKPolyline.

    The answer is an Objective-C version, so I tried to convert it to Swift, sample code:

    func polyLineWithEncodedString(encodedString: String) -> MKPolyline {
            let bytes = (encodedString as NSString).UTF8String
            let length = encodedString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
            var idx: Int = 0
    
            var count = length / 4
            var coords = UnsafeMutablePointer.alloc(count)
            var coordIdx: Int = 0
    
            var latitude: Double = 0
            var longitude: Double = 0
    
            while (idx < length) {
                var byte = 0
                var res = 0
                var shift = 0
    
                do {
                    byte = bytes[idx++] - 0x3F
                    res |= (byte & 0x1F) << shift
                    shift += 5
                } while (byte >= 0x20)
    
                let deltaLat = ((res & 1) != 0x0 ? ~(res >> 1) : (res >> 1))
                latitude += Double(deltaLat)
    
                shift = 0
                res = 0
    
                do {
                    byte = bytes[idx++] - 0x3F
                    res |= (byte & 0x1F) << shift
                    shift += 5
                } while (byte >= 0x20)
    
                let deltaLon = ((res & 1) != 0x0 ? ~(res >> 1) : (res >> 1))
                longitude += Double(deltaLon)
    
                let finalLat: Double = latitude * 1E-5
                let finalLon: Double = longitude * 1E-5
    
                let coord = CLLocationCoordinate2DMake(finalLat, finalLon)
                coords[coordIdx++] = coord
    
                if coordIdx == count {
                    let newCount = count + 10
                    let temp = coords
                    coords.dealloc(count)
                    coords = UnsafeMutablePointer.alloc(newCount)
                    for index in 0..

    You can try the sample project from this GitHub link.

    Below is the image of using Google Direction API web service to render a route on MKMapView from San Francisco to San Jose.

    enter image description here

提交回复
热议问题