我正在尝试使用 Google 路线 API 获取路线。到目前为止我所做的一切都有效。我有搜索功能,可以保存搜索到的位置(使用谷歌的建议位置),然后它会在那里放置一个标记。
我刚刚添加了一些代码,这些代码将使用 Google Directions API 从特定位置(在本例中为我的当前位置)绘制地图。我的应用程序可以跟踪我的位置和所有内容,我没有遇到任何问题。
当我尝试创建在下面附上屏幕截图的 URL 时,我的保护声明中不断出现“错误:无法创建 URL”错误,但我还是有点困惑。它说 key= 的地方就是我输入我的 API 密钥的地方。我显然没有在此屏幕截图中包含它,因为这将使每个人都可以访问我的 API 密钥。
我继续并实际使用打印的 urlString(显示在控制台中)并将 URL 复制到我的网页,它运行良好。它显示了我希望它显示的内容(据我所知),甚至尝试在网页中没有密钥的情况下它仍然有效。有没有人遇到过这个问题?我已经做了传输安全域异常,所以那里没有问题。
我附上了下面的代码。currentLatitude/Longtitude 和 searchedLatitude/Longitude 都是 CLLocationDegrees 类型。Current 是我当前的位置坐标,并且 searched 是用户搜索位置时返回给我的坐标
let currLat = String(currentLatitude)
let currLong = String(currentLongitude)
let seLat = String(searchedLatitude)
let seLong = String(searchedLongitude)
let originCoordinateString = "\(currLat), \(currLong)"
let destinationCoordinateString = "\(seLat), \(seLong)"
print(currentLatitude)
print(currentLongitude)
print(searchedLatitude)
print(searchedLongitude)
let urlString = "http://maps.googleapis.com/maps/api/directions/json?origin=\(originCoordinateString)&destination=\(destinationCoordinateString)&sensor=false"
print(urlString)
guard let url = URL(string: urlString) else {
print(urlString)
print ("Error: cannot create URL")
return
}