Add a text label to a polygon in google maps for iOS swift

夙愿已清 提交于 2019-12-01 06:46:56

Your UIGraphics drawing method might not be correct, you can try the following code to make a new image from a text:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        super.viewDidLoad()

        let camera = GMSCameraPosition.cameraWithLatitude(40.712216,
            longitude: -74.22655, zoom: 10)
        let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        mapView.myLocationEnabled = true
        self.view = mapView

        addGroundOverlay(camera.target)
    }

    func newImage(text: String, size: CGSize) -> UIImage {

        let data = text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        let drawText = NSString(data: data!, encoding: NSUTF8StringEncoding)

        let textFontAttributes = [
            NSFontAttributeName: UIFont(name: "Helvetica Bold", size: 20)!,
            NSForegroundColorAttributeName: UIColor.redColor(),
        ]

        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        drawText?.drawInRect(CGRectMake(0, 0, size.width, size.height), withAttributes: textFontAttributes)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }

    func addGroundOverlay(position: CLLocationCoordinate2D) {

        let overlay = GMSGroundOverlay(position: position, icon: newImage("Hello StackOverflow", size: CGSizeMake(150.0, 150.0)), zoomLevel: 10)
        overlay.bearing = 0
        overlay.map = (self.view as! GMSMapView)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I've found personally that the easiest way to do this is by adding a GMSMarker with a UILabel as it's iconView property.

            let labelMarker = GMSMarker(position: coordinate)
            let label = UILabel()
            label.text = "Hello friends"
            label.sizeToFit()
            labelMarker.iconView = label
            labelMarker.map = mapView

This approach can run into performance issues if you're adding a TON of markers to the map, but it's very effective if you need to add some labels to a map.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!