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

iOS控制器中Google Maps地图不显示问题排查及修复方案

问题排查与修复方案

我帮你梳理下代码里的几个关键问题,这些都是导致地图无法正常显示的核心原因:

1. 地图相机经纬度赋值错误

在创建GMSCameraPosition时,你把经度(longitude)错误地重复使用了纬度(latitude)的值,这会让地图定位到一个完全错误的坐标点:

// 错误代码
let camera = GMSCameraPosition.camera(withLatitude: (self.locManager.location?.coordinate.latitude)!, 
                                      longitude: (self.locManager.location?.coordinate.latitude)!, // 这里应该是longitude
                                      zoom: 140)

修复:把第二个参数改成self.locManager.location?.coordinate.longitude

2. 缩放级别设置过大

Google Maps的缩放范围通常是1(全球视图)到20(最精细的街景),你设置的zoom:140会让地图缩到完全看不到内容的程度,改成15左右的合理数值即可。

3. 强制解包存在崩溃风险

self.locManager.location可能为nil(比如权限未授权、定位失败时),直接用!强制解包会导致App崩溃。需要先判断location是否存在,再进行后续操作。

4. MapView的Frame设置错误

你把mapView的frame设为self.view.bounds,但最终是添加到containView里,这会导致mapView超出容器范围甚至被遮挡,应该用containView.bounds来匹配容器尺寸。

5. LocationManager代理方法签名不正确

在Swift 3及以后版本中,CLLocationManager的代理方法需要带有下划线前缀,你的方法签名缺少了_,导致方法不会被系统调用:

// 错误签名
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

// 正确签名
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

6. 缺少权限状态处理

用户可能会拒绝定位权限,这时候locManager.startUpdatingLocation()不会返回任何位置,需要添加授权状态监听,提示用户开启权限。


完整修复后的代码

import UIKit
import CoreLocation
import GoogleMaps

class CourseClass2: UIViewController, UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, CLLocationManagerDelegate {
    
    @IBOutlet weak var containView: UIView!
    let locManager = CLLocationManager()
    var mapView: GMSMapView? // 保存mapView引用,避免重复创建
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.locManager.delegate = self
        self.locManager.desiredAccuracy = kCLLocationAccuracyBest
        
        // 先检查权限状态
        checkLocationAuthorization()
    }
    
    // 检查定位权限
    func checkLocationAuthorization() {
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            locManager.requestWhenInUseAuthorization()
        case .authorizedWhenInUse, .authorizedAlways:
            locManager.startUpdatingLocation()
        case .denied, .restricted:
            // 提示用户开启权限
            let alert = UIAlertController(title: "需要定位权限", message: "请在设置中开启定位权限以显示当前位置", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "去设置", style: .default, handler: { _ in
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
            }))
            alert.addAction(UIAlertAction(title: "取消", style: .cancel))
            present(alert, animated: true)
        @unknown default:
            break
        }
    }
    
    // 修正后的代理方法签名
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // 取最新的位置
        guard let currentLocation = locations.last else { return }
        showCurrentLocationOnMap(with: currentLocation)
        locManager.stopUpdatingLocation()
    }
    
    // 处理权限状态变化
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        checkLocationAuthorization()
    }
    
    func showCurrentLocationOnMap(with location: CLLocation) {
        // 使用传入的位置,避免依赖locManager.location
        let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
                                              longitude: location.coordinate.longitude,
                                              zoom: 15) // 合理的缩放级别
        
        // 创建mapView并匹配containView的尺寸
        mapView = GMSMapView.map(withFrame: containView.bounds, camera: camera)
        mapView?.isMyLocationEnabled = true
        containView.addSubview(mapView!)
        
        // 添加当前位置标记
        let marker = GMSMarker()
        marker.position = camera.target
        marker.snippet = "Current location"
        marker.appearAnimation = .pop
        marker.map = mapView
    }
}

额外注意事项:

  • 确保你已经在Info.plist中添加了NSLocationWhenInUseUsageDescription键,并填写了权限申请说明。
  • 确认Google Maps的API Key已经正确配置到项目中(可在AppDelegate或Info.plist中设置)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:22:55