如要自訂地圖元件的外觀與風格,請使用雲端式地圖樣式設定地圖樣式,或是直接在程式碼中設定選項。
使用雲端式地圖樣式設定設定地圖樣式
使用雲端式地圖樣式設定,自訂地圖元件的外觀與風格。您可以在 Google Cloud 控制台上,為使用 Google 地圖的任何應用程式建立及編輯地圖樣式,完全不必變更程式碼。詳情請參閱「雲端式地圖樣式設定」。
ConsumerMapView
和 ConsumerMapFragment
類別都支援雲端式地圖樣式設定。如要使用雲端式地圖樣式設定,請確認所選的地圖轉譯器為 LATEST
。以下各節將舉例說明如何在專案中使用雲端地圖樣式。
ConsumerMapView
如要在 ConsumerMapView
中使用雲端地圖樣式,請在 GoogleMapOptions
上設定 mapId
欄位,並將 GoogleMapOptions
傳遞至 getConsumerGoogleMapAsync(ConsumerMapReadyCallback, Fragment, GoogleMapOptions) 或 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
在 ConsumerMapFragment 中使用雲端式地圖樣式設定的方式有兩種:
- 使用 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
動態執行
如要在 ConsumerMapFragment
中使用雲端式地圖樣式搭配 newInstance
,請在 GoogleMapOptions
上設定 mapId
欄位,並將 GoogleMapOptions
傳遞至 newInstance
。請參閱以下範例:
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 消費者行程分享地圖,請在建立 JourneySharingMapView
時指定 mapId
和其他 mapOptions
。
以下範例說明如何套用含有地圖 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
時設定地圖選項,藉此自訂地圖樣式。以下範例說明如何使用地圖選項為地圖設定樣式。如要進一步瞭解可設定的地圖選項,請參閱 Google Maps JavaScript API 參考資料中的 mapOptions
。
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 車隊追蹤程式庫,請按照下列步驟操作:
- 新增驗證權杖工廠的程式碼。
- 在
initMap()
函式中初始化位置資訊供應器。 - 在
initMap()
函式中初始化地圖檢視畫面。這個檢視畫面包含地圖。 - 將自訂項目移至地圖檢視初始化的回呼函式。
- 將位置程式庫新增至 API 載入器。
使用排程工作進行地圖取代的範例
以下範例說明如何使用現有地圖,並在其中為排程工作用途初始化位置提供者物件。在叫車服務用途中,程式碼類似,但您會使用 FleetEngineVehicleLocationProvider
而非 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>
如果您在碼頭 39 附近運作具有指定 ID 的外送車輛,現在會在地圖上顯示。