从Google Map API绘制方向

时间:2018-12-10 22:42:28

标签: ios swift google-maps-api-3

我正在尝试绘制从标记到另一个的方向线。我已经在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或请求有问题。请帮助我的先生和女士。

2 个答案:

答案 0 :(得分:1)

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

进行验证
print(json)

您应该在response数组为空的routes中看到这一点,

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

答案 1 :(得分:-3)

转到Google cloud console并创建一个新项目并启用Direction API。 API Libary 并将您的API密钥放入您的url
参见此Link,它可帮助您获取示例API和Google Direction API的响应。