ios - 从谷歌地图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 或请求有问题。请先生们和女士们帮帮我。
解决方案
我怀疑,您api key
无权使用此服务。您可以通过打印验证json
print(json)
你应该在数组为空的response
地方看到这个,routes
{
"error_message" = "This API project is not authorized to use this API.";
routes = (
);
status = "REQUEST_DENIED";
}
推荐阅读
- python - Selenium 无法访问 Google Compute Engine VM 上的“bet365”
- linux - 使用 apt list 命令输出到文件(Debian)
- json - 处理 JSON 数组
- mysql - 在 bash 脚本中为 mysql 用户创建限制字符
- angular - CK Editor 5 Paste From Word 插件不起作用
- dns - Gmail 中的“发送邮件”功能(在技术层面上)是如何工作的?
- assembly - 汇编语言高级计算器
- javascript - 如何获取整个 HTML 下拉列表的值
- unit-testing - Quarkus 忽略依赖项进行测试
- python - 如何从递归函数中获取数字列表并将其作为列表返回?