Tạo kiểu cho bản đồ

Để tuỳ chỉnh giao diện của thành phần bản đồ, hãy tạo kiểu cho bản đồ của bạn bằng cách sử dụng định kiểu bản đồ dựa trên đám mây hoặc bằng cách thiết lập các tuỳ chọn trực tiếp trong mã.

Tạo kiểu cho bản đồ bằng kiểu bản đồ dựa trên đám mây

Tuỳ chỉnh giao diện của thành phần bản đồ bằng cách sử dụng bản đồ trên đám mây tạo kiểu. Bạn có thể tạo và chỉnh sửa kiểu bản đồ trên bảng điều khiển Google Cloud cho bất kỳ của ứng dụng sử dụng Google Maps mà không yêu cầu thay đổi mã. Để biết thêm thông tin, hãy xem Định kiểu bản đồ trên đám mây.

Cả hai thuộc tính ConsumerMapViewConsumerMapFragment các lớp hỗ trợ định kiểu bản đồ trên đám mây. Để sử dụng việc định kiểu bản đồ dựa trên đám mây, hãy đảm bảo rằng các bản đồ đã chọn trình kết xuất là LATEST. Các phần sau đây trình bày ví dụ về cách sử dụng định kiểu bản đồ dựa trên đám mây bằng dự án của bạn.

ConsumerMapView

Để sử dụng kiểu bản đồ dựa trên đám mây trong ConsumerMapView, hãy đặt giá trị Trường mapId trên GoogleMapOptions và truyền GoogleMapOptions đến getConsumerGoogleMapAsync(ConsumerMapReadyCallback, Fragment, GoogleMapOptions) or getConsumerGoogleMapAsync(ConsumerMapReadyCallback, FragmentActivity, GoogleMapOptions)

Ví dụ:

Java

public class SampleAppActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ConsumerMapView mapView = findViewById(R.id.consumer_map_view);

    if (mapView != null) {
      GoogleMapOptions optionsWithMapId = new GoogleMapOptions().mapId("map-id");
      mapView.getConsumerGoogleMapAsync(
          new ConsumerMapReadyCallback() {
            @Override
            public void onConsumerMapReady(@NonNull ConsumerGoogleMap consumerGoogleMap) {
              // ...
            }
          },
          /* fragmentActivity= */ this,
          /* googleMapOptions= */ optionsWithMapId);
    }
  }
}

Kotlin

class SampleAppActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val mapView = findViewById(R.id.consumer_map_view) as ConsumerMapView

    val optionsWithMapId = GoogleMapOptions().mapId("map-id")
    mapView.getConsumerGoogleMapAsync(
      object : ConsumerGoogleMap.ConsumerMapReadyCallback() {
        override fun onConsumerMapReady(consumerGoogleMap: ConsumerGoogleMap) {
          // ...
        }
      },
      /* fragmentActivity= */ this,
      /* googleMapOptions= */ optionsWithMapId)
  }
}

ConsumerMapFragment

Có hai cách để sử dụng định kiểu bản đồ dựa trên đám mây trong ConsumerMapFragments:

  • Tĩnh với XML.
  • Linh hoạt nhờ newInstance.

Tĩnh với XML

Để sử dụng định kiểu bản đồ dựa trên đám mây bằng XML trong ConsumerMapFragment, hãy thêm thuộc tính XML map:mapId bằng thuộc tính được chỉ định mapId. Hãy xem ví dụ sau:

<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:name="com.google.android.libraries.mapsplatform.transportation.consumer.view.ConsumerMapFragment"
    android:id="@+id/consumer_map_fragment"
    map:mapId="map-id"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Linh hoạt nhờ newInstance

Để sử dụng định kiểu bản đồ dựa trên đám mây bằng newInstance trong ConsumerMapFragment, đặt trường mapId trên GoogleMapOptions và truyền GoogleMapOptions thành newInstance. Hãy xem ví dụ sau:

Java

public class SampleFragmentJ extends Fragment {

  @Override
  public View onCreateView(
      @NonNull LayoutInflater inflater,
      @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.consumer_map_fragment, container, false);

    GoogleMapOptions optionsWithMapId = new GoogleMapOptions().mapId("map-id");
    ConsumerMapFragment consumerMapFragment = ConsumerMapFragment.newInstance(optionsWithMapId);

    getParentFragmentManager()
        .beginTransaction()
        .add(R.id.consumer_map_fragment, consumerMapFragment)
        .commit();

    consumerMapFragment.getConsumerGoogleMapAsync(
        new ConsumerMapReadyCallback() {
          @Override
          public void onConsumerMapReady(@NonNull ConsumerGoogleMap consumerGoogleMap) {
            // ...
          }
        });

    return view;
  }
}

Kotlin

class SampleFragment : Fragment() {
  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?): View? {

    val view = inflater.inflate(R.layout.consumer_map_fragment, container, false)

    val optionsWithMapId = GoogleMapOptions().mapId("map-id")
    val consumerMapFragment = ConsumerMapFragment.newInstance(optionsWithMapId)

    parentFragmentManager
      .beginTransaction()
      .add(R.id.consumer_map_fragment, consumerMapFragment)
      .commit()

    consumerMapFragment.getConsumerGoogleMapAsync(
      object : ConsumerMapReadyCallback() {
        override fun onConsumerMapReady(consumerGoogleMap: ConsumerGoogleMap) {
          // ...
        }
      })

    return view
  }
}

Để áp dụng kiểu bản đồ cho bản đồ chia sẻ hành trình của người tiêu dùng sử dụng JavaScript, hãy chỉ định một mapId và bất kỳ loại nào khác mapOptions khi bạn tạo JourneySharingMapView.

Các ví dụ sau đây minh hoạ cách áp dụng kiểu bản đồ bằng mã bản đồ.

JavaScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    mapId: 'YOUR_MAP_ID'
  }
  // Any other styling options.
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    mapId: 'YOUR_MAP_ID'
  }
  // Any other styling options.
});

Tạo kiểu cho bản đồ ngay trong mã của riêng bạn

Bạn cũng có thể tuỳ chỉnh kiểu bản đồ bằng cách đặt tuỳ chọn bản đồ khi bạn tạo JourneySharingMapView. Các ví dụ sau đây minh hoạ cách tạo kiểu cho bản đồ bằng cách sử dụng tuỳ chọn bản đồ. Để biết thêm thông tin về những tùy chọn bản đồ mà bạn có thể đặt, hãy xem mapOptions trong tài liệu tham khảo API JavaScript của Google Maps.

JavaScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    styles: [
      {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
          { "color": "#CCFFFF" }
        ]
      }
    ]
  }
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    styles: [
      {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
          { "color": "#CCFFFF" }
        ]
      }
    ]
  }
});

Tắt tính năng điều chỉnh tự động

Bạn có thể ngăn bản đồ tự động điều chỉnh khung nhìn vừa với xe và tuyến đường dự kiến bằng cách tắt tính năng điều chỉnh tự động. Ví dụ sau đây cho biết cách tắt tính năng tự động điều chỉnh khi bạn thiết lập chế độ chia sẻ hành trình chế độ xem bản đồ.

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  automaticViewportMode:
      google.maps.journeySharing
          .AutomaticViewportMode.NONE,
  ...
});

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  automaticViewportMode:
      google.maps.journeySharing
          .AutomaticViewportMode.NONE,
  ...
});

Thay thế bản đồ hiện có

Bạn có thể thay thế một bản đồ hiện có bao gồm các điểm đánh dấu hoặc các tuỳ chỉnh khác mà không mất đi những tuỳ chỉnh đó.

Ví dụ: giả sử bạn có trang web có google.maps.Map chuẩn thực thể nơi một điểm đánh dấu được hiển thị:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
           /* Set the size of the div element that contains the map */
          #map {
            height: 400px;  /* The height is 400 pixels */
            width: 100%;  /* The width is the width of the web page */
           }
        </style>
      </head>
      <body>
        <h3>My Google Maps Demo</h3>
        <!--The div element for the map -->
        <div id="map"></div>
        <script>
    // Initialize and add the map
    function initMap() {
      // The location of Pier 39 in San Francisco
      var pier39 = {lat: 37.809326, lng: -122.409981};
      // The map, initially centered at Mountain View, CA.
      var map = new google.maps.Map(document.getElementById('map'));
      map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});

      // The marker, now positioned at Pier 39
      var marker = new google.maps.Marker({position: pier39, map: map});
    }
        </script>
        <!-- Load the API from the specified URL.
           * The async attribute allows the browser to render the page while the API loads.
           * The key parameter will contain your own API key (which is not needed for this tutorial).
           * The callback parameter executes the initMap() function.
        -->
        <script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
        </script>
      </body>
    </html>

Cách thêm thư viện kênh phát hành nhóm JavaScript:

  1. Thêm mã cho nhà máy mã thông báo xác thực.
  2. Khởi chạy trình cung cấp vị trí trong hàm initMap().
  3. Khởi động chế độ xem bản đồ trong hàm initMap(). Chế độ xem chứa bản đồ.
  4. Chuyển chế độ tuỳ chỉnh của bạn vào hàm callback để khởi chạy chế độ xem bản đồ.
  5. Thêm thư viện vị trí vào trình tải API.

Ví dụ về việc thay thế bản đồ bằng cách sử dụng tác vụ đã lên lịch

Các ví dụ sau cho thấy cách sử dụng bản đồ hiện có mà bạn khởi tạo đối tượng trình cung cấp vị trí cho một trường hợp sử dụng tác vụ đã lên lịch. Mã này tương tự cho các trường hợp sử dụng chuyến đi theo yêu cầu, ngoại trừ việc bạn sử dụng FleetEngineVehicleLocationProvider thay vì FleetEngineDeliveryVehicleLocationProvider.

    <!DOCTYPE html>
    <html>
      <head>
        <style>
           /* Set the size of the div element that contains the map */
          #map {
            height: 400px;  /* The height is 400 pixels */
            width: 100%;  /* The width is the width of the web page */
           }
        </style>
      </head>
      <body>
        <h3>My Google Maps Demo</h3>
        <!--The div element for the map -->
        <div id="map"></div>
        <script>
    let locationProvider;

    // (1) Authentication Token Fetcher
    function authTokenFetcher(options) {
      // options is a record containing two keys called
      // serviceType and context. The developer should
      // generate the correct SERVER_TOKEN_URL and request
      // based on the values of these fields.
      const response = await fetch(SERVER_TOKEN_URL);
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          const data = await response.json();
          return {
            token: data.Token,
            expiresInSeconds: data.ExpiresInSeconds
          };
    }

    // Initialize and add the map
    function initMap() {
      // (2) Initialize location provider. Use FleetEngineDeliveryVehicleLocationProvider
      // as appropriate.
      locationProvider = new google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProvider({
        YOUR_PROVIDER_ID,
        authTokenFetcher,
      });

      // (3) Initialize map view (which contains the map).
      const mapView = new google.maps.journeySharing.JourneySharingMapView({
        element: document.getElementById('map'),
        locationProviders: [locationProvider],
        // any styling options
      });

    mapView.addListener('ready', () => {
      locationProvider.deliveryVehicleId = DELIVERY_VEHICLE_ID;

        // (4) Add customizations like before.
        // The location of Pier 39 in San Francisco
          var pier39 = {lat: 37.809326, lng: -122.409981};
        // The map, initially centered at Mountain View, CA.
        var map = mapView.map;
        map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
        // The marker, now positioned at Pier 39
        var marker = new google.maps.Marker({position: pier39, map: map});
      };
    }
        </script>
        <!-- Load the API from the specified URL
          * The async attribute allows the browser to render the page while the API loads
          * The key parameter will contain your own API key (which is not needed for this tutorial)
          * The callback parameter executes the initMap() function
          *
          * (5) Add the journey sharing library to the API loader, which includes Fleet Tracking functionality.
        -->
        <script defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
        </script>
      </body>
    </html>

Nếu bạn vận hành xe giao hàng bằng ID được chỉ định gần Cầu tàu 39, nó hiện được hiển thị trên bản đồ.

Các bước tiếp theo