首页 > 解决方案 > 从谷歌地图API绘制方向

问题描述

我正在尝试绘制从标记到另一个的方向线。我已经在 google map api 中打开了方向。我在这里得到了这个功能(SO)。我明白它在做什么,但我无法让它工作。返回为routes array空。我已经尝试了多个测试点。这是功能:

func drawPath2(origin: CLLocationCoordinate2D, destination: CLLocationCoordinate2D)
{

let origin = "\(origin.latitude),\(origin.longitude)"
    let destination = "\(destination.latitude),\(destination.longitude)"
    let apiKey = "Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

    guard let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ") else {return}

    Alamofire.request(url).responseJSON { response in
        print(response.request)  // original URL request
        print(response.response) // HTTP URL response
        print(response.data)     // server data
        print(response.result)   // result of response serialization

        let json = try! JSON(data: response.data!)
        let routes = json["routes"].arrayValue

        //remove this after test
        print(routes.count)

        for route in routes
        {
            let routeOverviewPolyline = route["overview_polyline"].dictionary
            let points = routeOverviewPolyline?["points"]?.stringValue
            let path = GMSMutablePath.init(fromEncodedPath: points!)
            let polyline = GMSPolyline.init(path: path)
            polyline.map = self.mapView
        }
    }
}

这是 print() 结果:

Optional(https://maps.googleapis.com/maps/api/directions/json?origin=49.18705,-123.107261&destination=49.1844,-123.1052&mode=driving&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ) Optional(<NSHTTPURLResponse: 0x6000024c5ba0> { URL: https://maps.googleapis.com/maps/api/directions/json?origin=49.18705,-123.107261&destination=49.1844,-123.1052&mode=driving&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ } { Status Code: 200, Headers { "Cache-Control" = ( "no-cache, must-revalidate" ); "Content-Encoding" = ( gzip ); "Content-Length" = ( 130 ); "Content-Type" = ( "application/json; charset=UTF-8" ); Date = ( "Mon, 10 Dec 2018 22:28:52 GMT" ); Expires = ( "Fri, 01 Jan 1990 00:00:00 GMT" ); Pragma = ( "no-cache" ); Server = ( mafe ); Vary = ( "Accept-Language" ); "alt-svc" = ( "quic=\":443\"; ma=2592000; v=\"44,43,39,35\"" ); "x-frame-options" = ( SAMEORIGIN ); "x-xss-protection" = ( "1; mode=block" ); } }) Optional(129 bytes) SUCCESS 0

我根本看不到data那里。我认为 URL 或请求有问题。请先生们和女士们帮帮我。

标签: iosswiftgoogle-maps-api-3

解决方案


我怀疑,您api key无权使用此服务。您可以通过打印验证json

print(json)

你应该在数组为空的response地方看到这个,routes

{
    "error_message" = "This API project is not authorized to use this API.";
    routes =     (
    );
    status = "REQUEST_DENIED";
}

推荐阅读