지도 스타일 지정

지도 구성요소의 디자인을 맞춤설정하려면 지도의 스타일을 지정하세요. 클라우드 기반 지도 스타일 지정을 사용하거나 코드에서 직접 옵션을 설정하여

클라우드 기반 지도 스타일 지정으로 지도 스타일 지정

클라우드 기반 지도를 사용하여 지도 구성요소의 디자인 맞춤설정 제공합니다. Google Cloud 콘솔에서 원하는 지도 스타일을 만들고 수정할 수 있습니다. 할 수 있습니다. 자세한 내용은 클라우드 기반 지도 스타일 지정

그리고 ConsumerMapView 드림 및 ConsumerMapFragment 클래스는 클라우드 기반 지도 스타일 지정을 지원합니다. 클라우드 기반 지도 스타일 지정을 사용하려면 선택한 지도가 렌더기는 LATEST입니다. 다음 섹션에서는 클라우드 기반 지도 스타일 지정 기능을 프로젝트에 사용할 수 있습니다.

ConsumerMapView

ConsumerMapView에서 클라우드 기반 지도 스타일 지정을 사용하려면 GoogleMapOptionsmapId 필드로 대체되고 GoogleMapOptionsgetConsumerGoogleMapAsync(ConsumerMapReadyCallback, Fragment, GoogleMapOptions) or getConsumerGoogleMapAsync(ConsumerMapReadyCallback, FragmentActivity, GoogleMapOptions)

자바

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

다음 두 가지 방법으로 클라우드 기반 지도 스타일 지정을 사용할 수 있습니다. ConsumerMapFragments:

  • 정적으로 XML을 사용합니다.
  • newInstance를 사용하여 동적으로

XML을 사용하여 정적으로

ConsumerMapFragment, 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로 클라우드 기반 지도 스타일 지정을 사용하려면 다음 단계를 따르세요. ConsumerMapFragment: GoogleMapOptionsmapId 필드를 설정하고 GoogleMapOptions에서 newInstance(으)로 아래 예를 참고하세요.

자바

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로 지도 스타일을 적용하는 방법을 보여줍니다.

자바스크립트

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 다음 예는 다음을 사용하여 지도의 스타일을 지정하는 방법을 보여줍니다. 지도 옵션 설정할 수 있는 지도 옵션에 대한 자세한 내용은 다음을 참고하세요. mapOptions 드림 참조하세요.

자바스크립트

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

자동 맞추기 사용 중지

지도가 표시 영역을 차량에 자동으로 맞추지 않도록 할 수 있습니다. 예측 경로 데이터를 얻는 데 도움이 됩니다. 다음 예를 참고하세요. 여정 공유를 구성할 때 자동 적합을 사용 중지하는 방법을 보여줍니다. 지도뷰입니다.

자바스크립트

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 Fleet 트랙 라이브러리를 추가하려면 다음 안내를 따르세요.

  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>

운송업체에서 배송 차량을 지정된 ID가 있으면 지도에 렌더링됩니다.

다음 단계