Vẽ hình nhiều đường trên bản đồ
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Hiển thị bản đồ của Nam Thái Bình Dương với ảnh động của các đa tuyến màu đỏ và xanh lục thay đổi vị trí và kích thước.
Bắt đầu
Trước khi có thể thử mã mẫu, bạn phải định cấu hình môi trường phát triển.
Để biết thêm thông tin, hãy xem Mẫu mã SDK Bản đồ dành cho iOS.
Xem mã
Swift
import GoogleMaps
import UIKit
final class PolylinesViewController: UIViewController {
private lazy var styles: [GMSStrokeStyle] = {
let greenStyle = GMSStrokeStyle.gradient(from: .green, to: UIColor.green.withAlphaComponent(0))
let redStyle = GMSStrokeStyle.gradient(from: UIColor.red.withAlphaComponent(0), to: .red)
return [greenStyle, redStyle, GMSStrokeStyle.solidColor(UIColor(white: 0, alpha: 0))]
}()
private var pathLength: Double = 0
private var pos: Double = 0
private var polylines: [GMSPolyline] = []
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -30, longitude: -175, zoom: 3)
return GMSMapView(frame: .zero, camera: camera)
}()
override func loadView() {
view = mapView
mapView.accessibilityElementsHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
var path = GMSMutablePath()
path.addLatitude(-33.866901, longitude: 151.195988)
path.addLatitude(-18, longitude: 179)
path.addLatitude(21.291982, longitude: -157.821856)
path.addLatitude(37.423802, longitude: -122.091859)
path.addLatitude(-12, longitude: -77)
path.addLatitude(-33.866901, longitude: 151.195988)
path = path.pathOffset(byLatitude: -30, longitude: 0)
pathLength = path.length(of: .geodesic) / 21
for i in 0..<30 {
let polyline = GMSPolyline(path: path.pathOffset(byLatitude: Double(i) * 1.5, longitude: 0))
polyline.strokeWidth = 8
polyline.geodesic = true
polyline.map = mapView
polylines.append(polyline)
}
animatePath()
}
// Updates the path style every 0.1 seconds.
private func animatePath() {
polylines.forEach {
if let path = $0.path {
$0.spans = GMSStyleSpansOffset(path, styles, [NSNumber(value: pathLength)], .geodesic, pos)
}
}
pos -= 50000
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.animatePath()
}
}
}
Objective-C
#import "GoogleMapsDemos/Samples/PolylinesViewController.h"
#import <GoogleMaps/GoogleMaps.h>
static CLLocationCoordinate2D kSydneyAustralia = {-33.866901, 151.195988};
static CLLocationCoordinate2D kHawaiiUSA = {21.291982, -157.821856};
static CLLocationCoordinate2D kFiji = {-18, 179};
static CLLocationCoordinate2D kMountainViewUSA = {37.423802, -122.091859};
static CLLocationCoordinate2D kLimaPeru = {-12, -77};
static bool kAnimate = true;
@implementation PolylinesViewController {
NSArray *_styles;
NSArray *_lengths;
NSArray *_polys;
double _pos, _step;
GMSMapView *_mapView;
}
- (void)tick {
for (GMSPolyline *poly in _polys) {
poly.spans = GMSStyleSpansOffset(poly.path, _styles, _lengths, kGMSLengthGeodesic, _pos);
}
_pos -= _step;
if (kAnimate) {
__weak id weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 10), dispatch_get_main_queue(),
^{
[weakSelf tick];
});
}
}
- (void)initLines {
if (!_polys) {
NSMutableArray *polys = [NSMutableArray array];
GMSMutablePath *path = [GMSMutablePath path];
[path addCoordinate:kSydneyAustralia];
[path addCoordinate:kFiji];
[path addCoordinate:kHawaiiUSA];
[path addCoordinate:kMountainViewUSA];
[path addCoordinate:kLimaPeru];
[path addCoordinate:kSydneyAustralia];
path = [path pathOffsetByLatitude:-30 longitude:0];
_lengths = @[ @([path lengthOfKind:kGMSLengthGeodesic] / 21) ];
for (int i = 0; i < 30; ++i) {
GMSPolyline *poly = [[GMSPolyline alloc] init];
poly.path = [path pathOffsetByLatitude:(i * 1.5) longitude:0];
poly.strokeWidth = 8;
poly.geodesic = YES;
poly.map = _mapView;
[polys addObject:poly];
}
_polys = polys;
}
}
- (void)viewDidLoad {
[super viewDidLoad];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-30 longitude:-175 zoom:3];
GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView.accessibilityElementsHidden = YES;
self.view = mapView;
_mapView = mapView;
CGFloat alpha = 1;
UIColor *green = [UIColor colorWithRed:0 green:1 blue:0 alpha:alpha];
UIColor *greenTransp = [UIColor colorWithRed:0 green:1 blue:0 alpha:0];
UIColor *red = [UIColor colorWithRed:1 green:0 blue:0 alpha:alpha];
UIColor *redTransp = [UIColor colorWithRed:1 green:0 blue:0 alpha:0];
GMSStrokeStyle *grad1 = [GMSStrokeStyle gradientFromColor:green toColor:greenTransp];
GMSStrokeStyle *grad2 = [GMSStrokeStyle gradientFromColor:redTransp toColor:red];
_styles = @[
grad1,
grad2,
[GMSStrokeStyle solidColor:[UIColor colorWithWhite:0 alpha:0]],
];
_step = 50000;
[self initLines];
[self tick];
}
@end
Chạy ứng dụng mẫu đầy đủ trên máy
Ứng dụng mẫu SDK Bản đồ dành cho iOS có sẵn dưới dạng tài nguyên lưu trữ để tải xuống trên GitHub.
Hãy làm theo các bước sau để cài đặt và dùng thử ứng dụng mẫu Maps SDK cho iOS.
- Chạy
git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git
để nhân bản kho lưu trữ mẫu vào một thư mục cục bộ.
Mở cửa sổ dòng lệnh, chuyển đến thư mục mà bạn đã nhân bản các tệp mẫu và đi sâu vào thư mục GoogleMaps:
Swift
cd maps-sdk-for-ios-samples-main/GoogleMaps-Swift
pod install
open GoogleMapsSwiftDemos.xcworkspace
Objective-C
cd maps-sdk-for-ios-samples-main/GoogleMaps
pod install
open GoogleMapsDemos.xcworkspace
- Trong Xcode, hãy nhấn vào nút biên dịch để tạo ứng dụng bằng lược đồ hiện tại. Bản dựng sẽ tạo ra lỗi, nhắc bạn nhập khoá API trong tệp
SDKConstants.swift
cho Swift hoặc tệp SDKDemoAPIKey.h
cho Objective-C.
- Lấy khoá API từ dự án của bạn bằng cách bật SDK Bản đồ dành cho iOS.
- Chỉnh sửa tệp
SDKConstants.swift
cho Swift hoặc tệp SDKDemoAPIKey.h
cho Objective-C và dán khoá API vào định nghĩa của hằng số apiKey
hoặc kAPIKey
. Ví dụ:
Swift
static let apiKey = "YOUR_API_KEY"
Objective-C
static NSString *const kAPIKey = @"YOUR_API_KEY";
- Trong tệp
SDKConstants.swift
(Swift) hoặc tệp SDKDemoAPIKey.h
(Objective-C), hãy xoá dòng sau vì dòng này dùng để đăng ký vấn đề do người dùng xác định:
Swift
#error (Register for API Key and insert here. Then delete this line.)
Objective-C
#error Register for API Key and insert here.
- Tạo bản dựng và chạy dự án. Cửa sổ trình mô phỏng iOS sẽ xuất hiện, hiển thị danh sách Bản minh hoạ SDK Bản đồ.
- Chọn một trong các tuỳ chọn hiển thị để thử nghiệm một tính năng của SDK Bản đồ dành cho iOS.
- Nếu bạn được nhắc cho phép GoogleMapsDemos truy cập vào vị trí của bạn, hãy chọn Cho phép.
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2025-08-31 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-31 UTC."],[[["\u003cp\u003eThis sample demonstrates animating the style of a polyline on a map using the Google Maps SDK for iOS.\u003c/p\u003e\n"],["\u003cp\u003eThe animation is achieved by dynamically updating the \u003ccode\u003eGMSStyleSpansOffset\u003c/code\u003e of the polylines based on position and style.\u003c/p\u003e\n"],["\u003cp\u003eThe sample code provides implementations in both Swift and Objective-C.\u003c/p\u003e\n"],["\u003cp\u003eYou can clone the sample app repository, install dependencies via CocoaPods, build the project, and run it on an iOS simulator.\u003c/p\u003e\n"],["\u003cp\u003eEnsure to obtain and configure your API key before building and running the sample app.\u003c/p\u003e\n"]]],[],null,["Displays a map of the south Pacific Ocean with an animation of red and green polylines changing their position and size.\n\nGet started\n\nBefore you can try the sample code, you must configure your development environment.\nFor more information, see [Maps SDK for iOS code samples](/maps/documentation/ios-sdk/examples).\n\nView the code \n\nSwift \n\n```swift\nimport GoogleMaps\nimport UIKit\n\nfinal class PolylinesViewController: UIViewController {\n private lazy var styles: [GMSStrokeStyle] = {\n let greenStyle = GMSStrokeStyle.gradient(from: .green, to: UIColor.green.withAlphaComponent(0))\n let redStyle = GMSStrokeStyle.gradient(from: UIColor.red.withAlphaComponent(0), to: .red)\n return [greenStyle, redStyle, GMSStrokeStyle.solidColor(UIColor(white: 0, alpha: 0))]\n }()\n private var pathLength: Double = 0\n private var pos: Double = 0\n private var polylines: [GMSPolyline] = []\n\n private lazy var mapView: GMSMapView = {\n let camera = GMSCameraPosition(latitude: -30, longitude: -175, zoom: 3)\n return GMSMapView(frame: .zero, camera: camera)\n }()\n\n override func loadView() {\n view = mapView\n mapView.accessibilityElementsHidden = true\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n var path = GMSMutablePath()\n path.addLatitude(-33.866901, longitude: 151.195988)\n path.addLatitude(-18, longitude: 179)\n path.addLatitude(21.291982, longitude: -157.821856)\n path.addLatitude(37.423802, longitude: -122.091859)\n path.addLatitude(-12, longitude: -77)\n path.addLatitude(-33.866901, longitude: 151.195988)\n path = path.pathOffset(byLatitude: -30, longitude: 0)\n pathLength = path.length(of: .geodesic) / 21\n for i in 0..\u003c30 {\n let polyline = GMSPolyline(path: path.pathOffset(byLatitude: Double(i) * 1.5, longitude: 0))\n polyline.strokeWidth = 8\n polyline.geodesic = true\n polyline.map = mapView\n polylines.append(polyline)\n }\n animatePath()\n }\n\n // Updates the path style every 0.1 seconds.\n private func animatePath() {\n polylines.forEach {\n if let path = $0.path {\n $0.spans = GMSStyleSpansOffset(path, styles, [NSNumber(value: pathLength)], .geodesic, pos)\n }\n }\n pos -= 50000\n\n DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {\n self.animatePath()\n }\n }\n}https://github.com/googlemaps-samples/maps-sdk-for-ios-samples/blob/86408feffd008565cd2cafce8aff3dc27f1f41bb/GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/PolylinesViewController.swift#L14-L72\n \n```\n\nObjective-C \n\n```objective-c\n#import \"GoogleMapsDemos/Samples/PolylinesViewController.h\"\n\n#import \u003cGoogleMaps/GoogleMaps.h\u003e\n\nstatic CLLocationCoordinate2D kSydneyAustralia = {-33.866901, 151.195988};\nstatic CLLocationCoordinate2D kHawaiiUSA = {21.291982, -157.821856};\nstatic CLLocationCoordinate2D kFiji = {-18, 179};\nstatic CLLocationCoordinate2D kMountainViewUSA = {37.423802, -122.091859};\nstatic CLLocationCoordinate2D kLimaPeru = {-12, -77};\nstatic bool kAnimate = true;\n\n@implementation PolylinesViewController {\n NSArray *_styles;\n NSArray *_lengths;\n NSArray *_polys;\n double _pos, _step;\n GMSMapView *_mapView;\n}\n\n- (void)tick {\n for (GMSPolyline *poly in _polys) {\n poly.spans = GMSStyleSpansOffset(poly.path, _styles, _lengths, kGMSLengthGeodesic, _pos);\n }\n _pos -= _step;\n if (kAnimate) {\n __weak id weakSelf = self;\n dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 10), dispatch_get_main_queue(),\n ^{\n [weakSelf tick];\n });\n }\n}\n\n- (void)initLines {\n if (!_polys) {\n NSMutableArray *polys = [NSMutableArray array];\n GMSMutablePath *path = [GMSMutablePath path];\n [path addCoordinate:kSydneyAustralia];\n [path addCoordinate:kFiji];\n [path addCoordinate:kHawaiiUSA];\n [path addCoordinate:kMountainViewUSA];\n [path addCoordinate:kLimaPeru];\n [path addCoordinate:kSydneyAustralia];\n path = [path pathOffsetByLatitude:-30 longitude:0];\n _lengths = @[ @([path lengthOfKind:kGMSLengthGeodesic] / 21) ];\n for (int i = 0; i \u003c 30; ++i) {\n GMSPolyline *poly = [[GMSPolyline alloc] init];\n poly.path = [path pathOffsetByLatitude:(i * 1.5) longitude:0];\n poly.strokeWidth = 8;\n poly.geodesic = YES;\n poly.map = _mapView;\n [polys addObject:poly];\n }\n _polys = polys;\n }\n}\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-30 longitude:-175 zoom:3];\n GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];\n mapView.accessibilityElementsHidden = YES;\n self.view = mapView;\n _mapView = mapView;\n\n CGFloat alpha = 1;\n UIColor *green = [UIColor colorWithRed:0 green:1 blue:0 alpha:alpha];\n UIColor *greenTransp = [UIColor colorWithRed:0 green:1 blue:0 alpha:0];\n UIColor *red = [UIColor colorWithRed:1 green:0 blue:0 alpha:alpha];\n UIColor *redTransp = [UIColor colorWithRed:1 green:0 blue:0 alpha:0];\n GMSStrokeStyle *grad1 = [GMSStrokeStyle gradientFromColor:green toColor:greenTransp];\n GMSStrokeStyle *grad2 = [GMSStrokeStyle gradientFromColor:redTransp toColor:red];\n _styles = @[\n grad1,\n grad2,\n [GMSStrokeStyle solidColor:[UIColor colorWithWhite:0 alpha:0]],\n ];\n _step = 50000;\n [self initLines];\n [self tick];\n}\n\n@end \nhttps://github.com/googlemaps-samples/maps-sdk-for-ios-samples/blob/86408feffd008565cd2cafce8aff3dc27f1f41bb/GoogleMaps/GoogleMapsDemos/Samples/PolylinesViewController.m#L16-L98\n\n \n```\n\nRun the full sample app locally\n\nThe Maps SDK for iOS sample app is available as a\n[download archive](https://github.com/googlemaps-samples/maps-sdk-for-ios-samples/archive/main.zip)\nfrom [GitHub](https://github.com/googlemaps-samples/maps-sdk-for-ios-samples/tree/main/GoogleMaps).\nFollow these steps to install and try the Maps SDK for iOS sample app.\n\n1. Run `git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git` to clone the samples repository into a local directory.\n2. Open a terminal window, navigate to the directory where you cloned the sample files, and\n drill down into the GoogleMaps directory:\n\n Swift \n\n cd maps-sdk-for-ios-samples-main/GoogleMaps-Swift\n pod install\n open GoogleMapsSwiftDemos.xcworkspace\n\n Objective-C \n\n cd maps-sdk-for-ios-samples-main/GoogleMaps\n pod install\n open GoogleMapsDemos.xcworkspace\n\n3. In Xcode, press the compile button to [build the app](https://developer.apple.com/documentation/xcode/building-and-running-an-app) with the current scheme. The build produces an error, prompting you to enter your API key in the `SDKConstants.swift` file for Swift or`SDKDemoAPIKey.h` file for Objective-C.\n4. [Get an API key](/maps/documentation/ios-sdk/get-api-key) from your project with the [Maps SDK for iOS enabled](/maps/documentation/ios-sdk/cloud-setup#enabling-apis).\n5. Edit the `SDKConstants.swift` file for Swift or`SDKDemoAPIKey.h` file for Objective-C and paste your API key into the definition of either the `apiKey` or `kAPIKey` constant. For example: \n\n Swift \n\n ```scdoc\n static let apiKey = \"YOUR_API_KEY\"\n ```\n\n Objective-C \n\n ```objective-c\n static NSString *const kAPIKey = @\"YOUR_API_KEY\";\n ```\n6. In the `SDKConstants.swift` file (Swift) or`SDKDemoAPIKey.h` file (Objective-C), remove the following line, because it's used to register the user-defined issue: \n\n Swift \n\n ```text\n #error (Register for API Key and insert here. Then delete this line.)\n ```\n\n Objective-C \n\n ```text\n #error Register for API Key and insert here.\n ```\n7. Build and run the project. The iOS simulator window appears, showing a list of **Maps SDK Demos**.\n8. Choose one of the options displayed, to experiment with a feature of the Maps SDK for iOS.\n9. If prompted to allow GoogleMapsDemos to access your location, choose **Allow**."]]