You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swift中从JSON API获取坐标并在谷歌地图上展示?

Got it, let's walk through the full implementation step by step—from parsing those coordinates from your API response to displaying them on Google Maps in Swift. I’ll build on the Alamofire code you already have.

完整实现步骤

1. 首先集成谷歌地图SDK

First, make sure you’ve got the Google Maps SDK added to your project. Here’s how to do it via CocoaPods (or use Swift Package Manager if you prefer):

  1. Add this to your Podfile:
    pod 'GoogleMaps'
    
  2. Run pod install in your terminal, then open the .xcworkspace file.
  3. Add your Google Maps API key to Info.plist:
    • Right-click Info.plist > Open As > Source Code
    • Add this snippet (replace YOUR_GOOGLE_MAPS_API_KEY with your actual key):
      <key>GMSApiKey</key>
      <string>YOUR_GOOGLE_MAPS_API_KEY</string>
      
  4. If you need to show the user’s current location, add location permissions to Info.plist:
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>We need your location to show you on the map</string>
    

2. 完善API响应的坐标解析

Let’s finish parsing the coordinates from your Alamofire response. I’ll assume your API returns endCoordinates with latitude and longitude fields (adjust the keys if your API uses different names):

import Alamofire
import GoogleMaps
import CoreLocation

class YourTripViewController: UIViewController {
    // Add a map view property (we'll set this up later)
    private var mapView: GMSMapView!
    
    // Your existing API request code, expanded:
    func fetchTripCoordinates() {
        let header: HTTPHeaders = ["Authorization": "Bearer YOUR_AUTH_TOKEN"] // Replace with your actual headers
        Alamofire.request(Constants.API.url("api/trip/mykey/startTrip"), 
                          method: .post, 
                          parameters: nil, 
                          encoding: URLEncoding.default, 
                          headers: header)
        .responseJSON { [weak self] response in
            guard let self = self else { return }
            self.progressHUD.dismiss(afterDelay: 0.5)
            
            switch response.result {
            case .success(let value):
                // Parse the JSON step by step
                guard let json = value as? [String: Any],
                      let responseDict = json["response"] as? [String: Any],
                      // Parse end coordinates (adjust keys to match your API)
                      let endCoords = responseDict["endCoordinates"] as? [String: Double],
                      let lat = endCoords["latitude"],
                      let lng = endCoords["longitude"] else {
                    print("Failed to parse JSON or coordinates")
                    return
                }
                
                // Convert to CLLocationCoordinate2D (Google Maps uses this format)
                let destinationCoordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
                
                // Now pass this coordinate to your map setup function
                self.setupMap(with: destinationCoordinate)
                
            case .failure(let error):
                print("API Request Failed: \(error.localizedDescription)")
                // Optional: Show an alert to the user
                let alert = UIAlertController(title: "Error", message: "Could not fetch trip data", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .default))
                self.present(alert, animated: true)
            }
        }
    }
}

3. 初始化并展示谷歌地图

Now let’s set up the GMSMapView and center it on your parsed coordinate:

extension YourTripViewController {
    private func setupMap(with destination: CLLocationCoordinate2D) {
        // Create a camera position focused on the destination
        let camera = GMSCameraPosition.camera(withLatitude: destination.latitude, 
                                              longitude: destination.longitude, 
                                              zoom: 15.0) // Zoom level 15 is good for street-level detail
        
        // Initialize the map view
        mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
        view.addSubview(mapView)
        
        // Optional: Enable user's current location (if you added the permission)
        mapView.isMyLocationEnabled = true
        mapView.settings.myLocationButton = true
    }
}

4. 添加标记点或路径

Option 1: Add a single marker at the destination

Add this inside the setupMap function:

let marker = GMSMarker(position: destination)
marker.title = "Your Destination"
marker.snippet = "This is where your trip ends"
marker.icon = GMSMarker.markerImage(with: .red) // Customize marker color
marker.map = mapView

Option 2: Draw a path if your API returns multiple coordinates

If your API returns a list of coordinates (e.g., a trip route), parse them into an array first, then draw a polyline:

// Example: Parse an array of coordinates from the API
guard let routeCoords = responseDict["routeCoordinates"] as? [[String: Double]] else { return }
let coordinateArray = routeCoords.compactMap { coords in
    guard let lat = coords["latitude"], let lng = coords["longitude"] else { return nil }
    return CLLocationCoordinate2D(latitude: lat, longitude: lng)
}

// Draw the polyline on the map
let path = GMSMutablePath()
coordinateArray.forEach { path.add($0) }
let polyline = GMSPolyline(path: path)
polyline.strokeColor = .systemBlue
polyline.strokeWidth = 3.0 // Adjust line thickness
polyline.map = mapView

5. 处理位置权限(可选)

If you want to show the user’s current location, add the CLLocationManagerDelegate to your view controller:

extension YourTripViewController: CLLocationManagerDelegate {
    private let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.startUpdatingLocation()
            mapView.isMyLocationEnabled = true
        }
    }
}

内容的提问来源于stack exchange,提问作者viper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:24:27