地図のスタイルを設定する

地図コンポーネントのデザインをカスタマイズするには、地図のスタイルを設定します。 Cloud ベースのマップのスタイル設定を使用するか、コードでオプションを直接設定します。

Cloud ベースのマップのスタイル設定で地図のスタイルを設定する

Cloud ベースのマップを使用して、マップ コンポーネントのデザインをカスタマイズする カスタマイズします。地図のスタイルの作成と編集は、任意の Google Cloud コンソールで Google マップを使用するアプリをすべて利用できます。コードを変更する必要はありません。 詳細については、次をご覧ください: Cloud ベースのマップのスタイル設定

また、 ConsumerMapView および ConsumerMapFragment Cloud ベースのマップのスタイル設定をサポートしています。 Cloud ベースのマップのスタイル設定を使用するには、選択したマップが レンダラが LATEST である。以降のセクションでは、 Cloud ベースのマップのスタイル設定をプロジェクトに追加できます。

ConsumerMapView

ConsumerMapView で Cloud ベースのマップのスタイル設定を使用するには、 GoogleMapOptionsmapId フィールドを指定し、GoogleMapOptionsgetConsumerGoogleMapAsync(ConsumerMapReadyCallback, Fragment, GoogleMapOptions) or getConsumerGoogleMapAsync(ConsumerMapReadyCallback, FragmentActivity, GoogleMapOptions)

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

Cloud ベースのマップのスタイル設定を使う方法は 2 つあります。 ConsumerMapFragments:

  • XML を使用して静的に。
  • newInstance を使用して動的に。

XML を使用して静的に行う

Cloud ベースのマップのスタイル設定を ConsumerMapFragment は、指定された ID を持つ map:mapId XML 属性を追加します。 mapId。次の例をご覧ください。

<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"/>

newInstance で動的に

newInstance を指定して Cloud ベースのマップのスタイル設定を使用するには、 ConsumerMapFragment は、GoogleMapOptionsmapId フィールドを設定し、 GoogleMapOptionsnewInstance。次の例をご覧ください。

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
  }
}

JavaScript カスタマー ジャーニーの共有地図に地図のスタイルを適用するには、 mapId、 その他 mapOptions これは JourneySharingMapView を作成するときです。

次の例は、マップ ID を使用して地図のスタイルを適用する方法を示しています。

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.
});

独自のコード内で直接地図のスタイルを設定

また、作成時に地図のオプションを設定して、地図のスタイルをカスタマイズすることもできます。 JourneySharingMapView。次の例は、API キーを使用して地図のスタイルを設定する方法を示しています。 地図のオプションを表示します。設定できる地図オプションについて詳しくは、 mapOptions (Google Maps JavaScript API リファレンス)をご覧ください。

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" }
        ]
      }
    ]
  }
});

自動適合を無効にする

地図が自動的にビューポートを車両にフィットさせないようにすることができます 予測ルートと推定ルートが表示されます次の例をご覧ください。 ジャーニーの共有を設定する際に自動適合を無効にする方法を示します。 使用できます。

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,
  ...
});

既存の地図を置き換える

マーカーやその他のカスタマイズ済みを含む既存の地図を置き換えることができます そのカスタマイズを維持できます

たとえば、標準の google.maps.Map を含むウェブページがあるとします。 次の要素です。

    <!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>

JavaScript フリート トラック ライブラリを追加するには:

  1. 認証トークン ファクトリのコードを追加します。
  2. initMap() 関数で位置情報プロバイダを初期化します。
  3. initMap() 関数でマップビューを初期化します。ビューには地図が含まれます。
  4. カスタマイズをマップビューの初期化用のコールバック関数に移動します。
  5. 位置情報ライブラリを API ローダに追加します。

スケジュールされたタスクを使用したマップ置換の例

次のサンプルは、既存の地図を使用して、 スケジュール済みタスクのユースケース用の位置情報プロバイダ オブジェクト。コードは次のようになります。 オンデマンドの旅程のユースケースに限らず、 FleetEngineVehicleLocationProviderFleetEngineDeliveryVehicleLocationProvider

    <!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>

配送車両を運送する場合、 地図上にレンダリングされます。

次のステップ