简体   繁体   中英

Adding a marker to a GMSMapView subview ios

I'm using the Google maps cocoapod and I can't figure out how to add a marker to my map. My map is a in subview. I put it in an array of views in viewDidLoad because for some reason I don't understand it always gets deleted before I can access it in methods outside of viewDidLoad - not ideal, but it was the only way I could figure out to save it. Anyway, I'm trying to add a marker. When I set the map to my main view like this it works fine:

var camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(37.7833, longitude: -122.4167, zoom: 6)
    var mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)

    self.view = mapView

    var marker = GMSMarker()
    marker.position = camera.target
    marker.map = mapView

However, when I try to add the marker to the subview I get from the array of subviews like this, it doesn't show up:

var tempMapSubView = self.views[0] as! GMSMapView

    var camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(37.7833, longitude: -122.4167, zoom: 6)
    var mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)

    tempMapSubView.camera = camera
    tempMapSubView = mapView

    var marker = GMSMarker()
    marker.position = camera.target
    marker.map = tempMapSubView

The array of subviews solution works really well with all the other stuff I'm trying to do. Thanks for your help!

Are you using google maps to get your device sensor via IP or GPS? If So it should automatically place a marker. You can then pass the marker coordinates to a string.

Your code is getting the map from self.views[0] , then creating a new map, then adding a marker to that new map. Then you do nothing with the new map, so it won't be displayed. Nothing has been added to the original map, and so you don't see the marker.

I think you need something like this:

var tempMapSubView = self.views[0] as! GMSMapView

var position = CLLocationCoordinate2DMake(37.7833, -122.4167)

var marker = GMSMarker()
marker.position = position
marker.map = tempMapSubView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM