如何从iOS中的谷歌地图获取静态图像

时间:2016-01-18 09:56:11

标签: ios swift google-maps

我使用谷歌地图api for iOS。我想得到特殊城市的静态图像并将其粘贴到UIImageView中。我该怎么做?

5 个答案:

答案 0 :(得分:15)

答案 1 :(得分:5)

    NSString *staticMapUrl = [NSString stringWithFormat:@"http://maps.google.com/maps/api/staticmap?markers=color:blue|%@,%@&%@&sensor=true",self.staticData.latitude, self.staticData.longitude, [NSString stringWithFormat:@"zoom=13&size=%dx%d",2*(int)mapFrame.size.width, 2*(int)mapFrame.size.height]];
    NSURL *mapUrl = [NSURL URLWithString:[staticMapUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:mapUrl]];

    UIImageView *mapImage = [[UIImageView alloc] initWithFrame:mapFrame];

这应该有所帮助。

答案 2 :(得分:1)

    Swift 3 =>
        let Width = 100
        let Height = 200

        let mapImageUrl = "https://maps.googleapis.com/maps/api/staticmap?center="
        let latlong = "18.495651759752, 73.809987567365"

        let mapUrl  = mapImageUrl + latlong

        let size = "&size=" +  "\(Int(Width))" + "x" +  "\(Int(Height))"
        let positionOnMap = "&markers=size:mid|color:red|" + latlong
        let staticImageUrl = mapUrl + size + positionOnMap

        if let urlStr : NSString = staticImageUrl.addingPercentEscapes(using:String.Encoding.utf8)! as NSString{
            // setImageFromURL 
       }

答案 3 :(得分:1)

使用Swift 3:

let lat = ..
let long = ..

let staticMapUrl: String = "http://maps.google.com/maps/api/staticmap?markers=color:red|\(lat),\(long)&\("zoom=13&size=\(2 * Int(cell.imgAddress.frame.size.width))x\(2 * Int(cell.imgAddress.frame.size.height))")&sensor=true"

let url = URL(string: staticMapUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)

do {
    let data = try NSData(contentsOf: url!, options: NSData.ReadingOptions())
    cell.imgAddress.image = UIImage(data: data as Data)
} catch {
    cell.imgAddress.image = UIImage()
}

答案 4 :(得分:1)

尝试一下。请注意,您必须从Google cloud

获取API密钥
let API_Key = //Your API Key.
let url = "https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=\(2 * Int(imgBanner.frame.size.width))x\(2 * Int(imgBanner.frame.size.height))&maptype=roadmap&key=\(API_Key)"
let mapUrl: NSURL = NSURL(string: staticMapUrl)!
self.imgBanner.sd_setImage(with: mapUrl as URL, placeholderImage: UIImage(named: "palceholder"))

始终检查浏览器中的链接以查看其是否工作正常,这表示图像中是否可见。