處理輕觸事件

讓資料地圖項目回應輕觸事件,並使用事件顯示已輕觸地圖項目的屬性值。

為輕觸事件套用樣式。

處理資料集圖層事件

這個範例顯示 ID 為 YOUR_DATASET_ID 資料集的資料地圖項目,並實作委派函式,顯示輕觸地圖項目的屬性值。

在這個範例中,資料集會顯示紐約市的公園。對於每個資料集地圖項目,對應至公園,資料集會包含名為 acres 的屬性,其中包含公園的表面區域。如果是輕觸的公園,顯示 acres 屬性的值。

Swift

class SampleViewController: UIViewController {

  private lazy var mapView: GMSMapView = GMSMapView(frame: .zero, mapID: GMSMapID(identifier: "YOUR_MAP_ID"), camera: GMSCameraPosition(latitude: 40.7, longitude: -74, zoom: 12))

  // Set default styles.
  view = mapView
  let style = FeatureStyle(fill: .green.withAlphaComponent(0.5), stroke: .green, strokeWidth: 2)
  mapView.datasetFeatureLayer(of: "YOUR_DATASET_ID").style = { _ in style }
  mapView.delegate = self
}

extension SampleViewController: GMSMapViewDelegate {
  func mapView(_ mapView: GMSMapView, didTap features: [Feature], in featureLayer: FeatureLayer<Feature>, atLocation: CLLocationCoordinate2D) {
    let toast = UIAlertController(title: "Area of park", message: (features.compactMap { ($0 as? DatasetFeature)?.datasetAttributes["acres"] }).joined(separator: ", "), preferredStyle: .alert)
    present(toast, animated: true, completion: nil)
  }
}

Objective-C


@interface SampleViewController: UIViewController <GMSMapViewDelegate>
@end

@implementation SampleViewController
- (void)loadView {
    GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero mapID:[GMSMapID mapIDWithIdentifier:@"YOUR_MAP_ID"] camera:[GMSCameraPosition cameraWithLatitude:40.7 longitude:-74 zoom:12]];
    mapView.delegete = self;

    // Set default styles.
    GMSFeatureStyle *style = [GMSFeatureStyle styleWithFillColor:[[UIColor greenColor] colorWithAlphaComponent:0.5] strokeColor:[UIColor greenColor] strokeWidth:2.0];
    [_mapView datasetFeatureLayerOfDatasetID:@"YOUR_DATASET_ID"].style = ^(GMSDatasetFeature *feature) { return style; };

    self.view = mapView;
}

- (void)mapView:(GMSMapView *)mapView didTapFeatures:(NSArray<id<GMSFeature>> *)features inFeatureLayer:(GMSFeatureLayer *)featureLayer atLocation:(CLLocationCoordinate2D)location {
  NSMutableArray<NSString *> *parkAreas = [NSMutableArray array];

  for (id<GMSFeature> feature in features) {
    if (![feature isKindOfClass:[GMSDatasetFeature class]]) { continue; }
    NSString *nameDefinedInDataset = ((GMSDatasetFeature *)feature).datasetAttributes[@"acres"];
    [parkAreas addObject:nameDefinedInDataset];
  }

  UIAlertController *toast = [UIAlertController alertControllerWithTitle:@"Area of park" message:[parkAreas componentsJoinedByString:@", "] preferredStyle:UIAlertControllerStyleAlert];
  [self presentViewController:toast animated:YES completion:nil];
}
@end