Określanie stylu mapy

Aby dostosować wygląd i styl komponentu map, określ styl mapy za pomocą stylu map w chmurze lub przez ustawienie opcji bezpośrednio w kodzie.

Nadaj mapie styl określania stylów map w chmurze

Dostosuj wygląd i styl komponentu map za pomocą map działających w chmurze stylu. W konsoli Google Cloud możesz tworzyć i edytować style mapy dla dowolnych w aplikacjach korzystających z Map Google bez konieczności wprowadzania zmian w kodzie. Więcej informacji: Definiowanie stylów map w Google Cloud

Zarówno ConsumerMapView oraz ConsumerMapFragment klas obsługują określanie stylów map w chmurze. Aby używać stylu map w chmurze, sprawdź, czy wybrane mapy mechanizm renderowania to LATEST. W poniższych sekcjach znajdziesz przykłady użycia funkcji stosować w projekcie stylowanie map w chmurze.

ConsumerMapView

Aby w ConsumerMapView używać stylu map opartego na chmurze, ustaw atrybut mapId w GoogleMapOptions i przekazać GoogleMapOptions do getConsumerGoogleMapAsync(ConsumerMapReadyCallback, Fragment, GoogleMapOptions) or getConsumerGoogleMapAsync(ConsumerMapReadyCallback, FragmentActivity, GoogleMapOptions)

Przykład

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

Istnieją 2 sposoby nadawania stylów map w chmurze ConsumerMapFragments:

  • Statycznie z użyciem pliku XML.
  • Dynamicznie z użyciem funkcji newInstance.

Statycznie za pomocą pliku XML

Aby użyć opartego na chmurze stylu map z użyciem kodu XML w pliku ConsumerMapFragment, dodaj atrybut XML map:mapId z określonym mapId Przyjrzyj się temu przykładowi:

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

Dynamicznie z użyciem newInstance

Aby używać stylu map w chmurze za pomocą usługi newInstance ConsumerMapFragment, ustaw pole mapId w domenie GoogleMapOptions i przekaż GoogleMapOptions do newInstance. Przyjrzyj się temu przykładowi:

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

Aby zastosować styl mapy do mapy udostępniania ścieżki klienta JavaScript, podaj mapId i wszystkie inne mapOptions podczas tworzenia JourneySharingMapView.

Poniższe przykłady pokazują, jak zastosować styl mapy za pomocą identyfikatora mapy.

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

Nadawanie stylu mapom bezpośrednio w własnym kodzie

Styl mapy możesz też dostosować, ustawiając opcje mapy podczas tworzenia JourneySharingMapView W poniższych przykładach pokazujemy, jak określić styl mapy za pomocą opcje mapy. Więcej informacji o dostępnych opcjach mapy znajdziesz w artykule mapOptions w dokumentacji JavaScript API Map Google.

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

Wyłącz automatyczne dopasowanie

Możesz wyłączyć automatyczne dopasowywanie widocznego obszaru do mapy do pojazdu. i przewidywanej trasy, wyłączając automatyczne dopasowanie. Przykład poniżej pokazuje, jak wyłączyć automatyczne dopasowanie podczas konfigurowania udostępniania podróży widoku mapy.

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

Zastępowanie istniejącej mapy

Możesz zastąpić istniejącą mapę, która zawiera znaczniki lub inne dostosowania bez utraty tych ustawień.

Załóżmy na przykład, że masz stronę internetową ze standardowym elementem google.maps.Map jednostka, w której jest wyświetlany znacznik:

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

Aby dodać bibliotekę śledzenia floty w języku JavaScript:

  1. Dodaj kod fabryki tokenów uwierzytelniania.
  2. Zainicjuj dostawcę lokalizacji w funkcji initMap().
  3. Zainicjuj widok mapy w funkcji initMap(). Widok zawiera mapę.
  4. Przenieś dostosowanie do funkcji wywołania zwrotnego na potrzeby zainicjowania widoku mapy.
  5. Dodaj bibliotekę lokalizacji do programu wczytującego interfejs API.

Przykład zastąpienia mapy przy użyciu zaplanowanych zadań

Poniższe przykłady pokazują, jak użyć istniejącej mapy, w której zainicjujesz obiektu dostawcy lokalizacji na potrzeby zaplanowanego zadania. Kod jest podobny w przypadku podróży na żądanie, z tym wyjątkiem, że używasz FleetEngineVehicleLocationProvider zamiast 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>

Jeśli masz pojazd dostawczy, o podanym identyfikatorze w pobliżu pierwiastka nr 39, teraz jest on renderowany na mapie.

Co dalej?