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

如何在Google Maps中为EClass数组元素批量添加标记?

Fixing Marker Addition for [EClass] Array in Google Maps iOS

Hey there, let's troubleshoot why your forEach call isn't adding markers for your places array. Here are the most common issues and fixes to get those markers showing up:

1. Check if places is populated (the #1 culprit for async data)

Your getNearbyPlaces method runs asynchronously—meaning if you call places.forEach directly in viewDidLoad, the array is probably still empty because the API request hasn't finished yet.

Fix: Move your marker-adding logic inside the completion handler of getNearbyPlaces, where you actually receive the populated places data:

override func viewDidLoad() {
    super.viewDidLoad()
    
    // Example coordinates—replace with your actual location
    let userLocation = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194)
    
    EClass.getNearbyPlaces(by: "cafe", coordinates: userLocation, radius: 1000, token: nil) { [weak self] response, error in
        guard let self = self, let response = response else {
            print("Failed to fetch places: \(error?.localizedDescription ?? "Unknown error")")
            return
        }
        
        // Assign the fetched places to your array
        self.places = response.places
        
        // Now add markers—this runs AFTER data is loaded
        DispatchQueue.main.async {
            self.places.forEach { place in
                self.addMarker(place: place)
            }
        }
    }
}
  • Use [weak self] to avoid memory leaks, and wrap the UI update in DispatchQueue.main.async to ensure it runs on the main thread (required for Google Maps UI changes).

2. Validate your addMarker method

Make sure your addMarker handles optional values properly and connects to the mapView correctly:

func addMarker(place: EClass) {
    // Guard against nil location (common if parsing fails)
    guard let placeLocation = place.location else {
        print("Skipping marker: Place \(place.placeId) has no valid location")
        return
    }
    
    let marker = GMSMarker(position: placeLocation)
    marker.title = place.name ?? "Unnamed Place"
    marker.snippet = place.vicinity ?? "No address available"
    marker.map = self.mapView // Ensure mapView is properly initialized/connected
}
  • Double-check that mapView is either connected via IBOutlet in Storyboard, or programmatically added to your view hierarchy before this method runs.

3. Verify EClass location parsing

Your EClass init might fail to parse location data for some places. Add debug prints to confirm:

init(placeInfo:[String: Any]) {
    placeId = placeInfo["place_id"] as! String
    // coordinates
    if let g = placeInfo[geometryKey] as? [String:Any] {
        if let l = g[locationKey] as? [String:Double] {
            if let lat = l[latitudeKey], let lng = l[longitudeKey] {
                location = CLLocationCoordinate2D.init(latitude: lat, longitude: lng)
                print("Successfully parsed location for \(name ?? "unknown place"): (\(lat), \(lng))")
            } else {
                print("Missing lat/lng for place ID: \(placeId)")
            }
        } else {
            print("No location data found for place ID: \(placeId)")
        }
    } else {
        print("No geometry data found for place ID: \(placeId)")
    }
    // name
    name = placeInfo[nameKey] as? String
}

This will help you spot if some places are missing the required geometry/location fields from the API response.

Quick Debug Checklist

  • Print places.count before calling forEach to confirm the array isn't empty
  • Ensure mapView is fully initialized (check for nil in addMarker)
  • Confirm all places have valid location values

内容的提问来源于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:41:19