Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Pour personnaliser l'apparence du composant Maps, appliquez un style à votre carte à l'aide des styles de cartes basés dans le cloud ou en définissant des options directement dans le code.
Styliser la carte avec les styles de cartes basés dans le cloud
Pour appliquer un style de carte à votre carte JavaScript de partage de trajets pour les consommateurs, spécifiez un mapId et tout autre mapOptions lorsque vous créez le JourneySharingMapView.
Les exemples suivants montrent comment appliquer un style de carte avec un ID de carte.
JavaScript
constmapView=newgoogle.maps.journeySharing.JourneySharingMapView({element:document.getElementById('map_canvas'),locationProviders:[locationProvider],mapOptions:{mapId:'YOUR_MAP_ID'}// Any other styling options.});
TypeScript
constmapView=newgoogle.maps.journeySharing.JourneySharingMapView({element:document.getElementById('map_canvas'),locationProviders:[locationProvider],mapOptions:{mapId:'YOUR_MAP_ID'}// Any other styling options.});
Appliquer un style aux cartes directement dans votre propre code
Vous pouvez également personnaliser le style de la carte en définissant des options de carte lorsque vous créez le JourneySharingMapView. Les exemples suivants montrent comment styliser une carte à l'aide des options de carte. Pour en savoir plus sur les options de carte que vous pouvez définir, consultez mapOptions dans la documentation de référence de l'API Google Maps JavaScript.
Vous pouvez empêcher la carte d'adapter automatiquement la fenêtre d'affichage au véhicule et à l'itinéraire prévu en désactivant l'adaptation automatique. L'exemple suivant montre comment désactiver l'ajustement automatique lorsque vous configurez la vue cartographique du partage de trajet.
Vous pouvez remplacer une carte existante qui inclut des repères ou d'autres personnalisations sans perdre ces personnalisations.
Par exemple, supposons que vous ayez une page Web avec une entité google.maps.Map standard sur laquelle un repère est affiché :
<!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>
Pour ajouter la bibliothèque JavaScript de suivi de flotte :
Ajoutez le code pour la fabrique de jetons d'authentification.
Initialisez un fournisseur de localisation dans la fonction initMap().
Initialisez la vue de carte dans la fonction initMap(). La vue contient la carte.
Déplacez votre personnalisation dans la fonction de rappel pour l'initialisation de la vue Plan.
Ajoutez la bibliothèque de localisation au chargeur d'API.
Exemple de remplacement de carte à l'aide de tâches planifiées
L'exemple suivant montre comment utiliser une carte existante dans laquelle vous initialisez l'objet du fournisseur de localisation pour un cas d'utilisation de tâche planifiée. Le code est similaire pour les cas d'utilisation de trajets à la demande, sauf que vous utilisez FleetEngineVehicleLocationProvider au lieu de 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>
Si vous conduisez un véhicule de livraison avec l'ID spécifié à proximité du Pier 39, il s'affiche désormais sur la carte.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eCustomize the appearance of the maps component using cloud-based map styling or by directly setting options in your code.\u003c/p\u003e\n"],["\u003cp\u003eCloud-based map styling allows you to manage map styles through the Google Cloud console without code changes, applying to \u003ccode\u003eConsumerMapView\u003c/code\u003e, \u003ccode\u003eConsumerMapFragment\u003c/code\u003e, and JavaScript consumer trip sharing maps.\u003c/p\u003e\n"],["\u003cp\u003eFor styling within your code, you can set map options when creating the \u003ccode\u003eJourneySharingMapView\u003c/code\u003e using parameters like \u003ccode\u003estyles\u003c/code\u003e or disabling automatic viewport fitting.\u003c/p\u003e\n"],["\u003cp\u003eReplace existing maps seamlessly while preserving customizations like markers by initializing a location provider and moving your customizations into the map view initialization callback function.\u003c/p\u003e\n"]]],[],null,["To customize the look and feel of the maps component, style your map\nusing cloud-based maps styling or by setting options directly in code.\n\nStyle the map with cloud-based maps styling\n\nTo apply a map style to your JavaScript consumer trip sharing map, specify a\n[`mapId`](/maps/documentation/javascript/reference/map#MapOptions.mapId) and\nany other\n[`mapOptions`](/maps/documentation/javascript/reference/map#MapOptions)\nwhen you create the `JourneySharingMapView`.\n| **Note:** You cannot change or add a `mapId` after the `JourneySharingMapView` has been instantiated.\n\nThe following examples show how to apply a map style with a map ID.\n\n\u003cbr /\u003e\n\nJavaScript\n\n\u003cbr /\u003e\n\n const mapView = new google.maps.journeySharing.JourneySharingMapView({\n element: document.getElementById('map_canvas'),\n locationProviders: [locationProvider],\n mapOptions: {\n mapId: 'YOUR_MAP_ID'\n }\n // Any other styling options.\n });\n\n\u003cbr /\u003e\n\nTypeScript\n\n\u003cbr /\u003e\n\n const mapView = new google.maps.journeySharing.JourneySharingMapView({\n element: document.getElementById('map_canvas'),\n locationProviders: [locationProvider],\n mapOptions: {\n mapId: 'YOUR_MAP_ID'\n }\n // Any other styling options.\n });\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nStyle maps directly in your own code\n\nYou can also customize map styling by setting map options when you create the\n`JourneySharingMapView`. The following examples show how to style a map using\nmap options. For more information on what map options you can set, see\n[`mapOptions`](/maps/documentation/javascript/reference/map#MapOptions)\nin the Google Maps JavaScript API reference.\n\n\u003cbr /\u003e\n\nJavaScript\n\n\u003cbr /\u003e\n\n const mapView = new google.maps.journeySharing.JourneySharingMapView({\n element: document.getElementById('map_canvas'),\n locationProviders: [locationProvider],\n mapOptions: {\n styles: [\n {\n \"featureType\": \"road.arterial\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n { \"color\": \"#CCFFFF\" }\n ]\n }\n ]\n }\n });\n\n\u003cbr /\u003e\n\nTypeScript\n\n\u003cbr /\u003e\n\n const mapView = new google.maps.journeySharing.JourneySharingMapView({\n element: document.getElementById('map_canvas'),\n locationProviders: [locationProvider],\n mapOptions: {\n styles: [\n {\n \"featureType\": \"road.arterial\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n { \"color\": \"#CCFFFF\" }\n ]\n }\n ]\n }\n });\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nDisable automatic fitting\n\nYou can stop the map from automatically fitting the viewport to the vehicle\nand anticipated route by disabling automatic fitting. The following example\nshows how to disable automatic fitting when you configure the journey sharing\nmap view. \n\nJavaScript \n\n const mapView = new\n google.maps.journeySharing.JourneySharingMapView({\n element: document.getElementById('map_canvas'),\n locationProviders: [locationProvider],\n automaticViewportMode:\n google.maps.journeySharing\n .AutomaticViewportMode.NONE,\n ...\n });\n\nTypeScript \n\n const mapView = new\n google.maps.journeySharing.JourneySharingMapView({\n element: document.getElementById('map_canvas'),\n locationProviders: [locationProvider],\n automaticViewportMode:\n google.maps.journeySharing\n .AutomaticViewportMode.NONE,\n ...\n });\n\nReplace an existing map\n\nYou can replace an existing map that includes markers or other customizations\nwithout losing those customizations.\n\nFor example, suppose you have a web page with a standard `google.maps.Map`\nentity on which a marker is shown: \n\n \u003c!DOCTYPE html\u003e\n \u003chtml\u003e\n \u003chead\u003e\n \u003cstyle\u003e\n /* Set the size of the div element that contains the map */\n #map {\n height: 400px; /* The height is 400 pixels */\n width: 100%; /* The width is the width of the web page */\n }\n \u003c/style\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003ch3\u003eMy Google Maps Demo\u003c/h3\u003e\n \u003c!--The div element for the map --\u003e\n \u003cdiv id=\"map\"\u003e\u003c/div\u003e\n \u003cscript\u003e\n // Initialize and add the map\n function initMap() {\n // The location of Pier 39 in San Francisco\n var pier39 = {lat: 37.809326, lng: -122.409981};\n // The map, initially centered at Mountain View, CA.\n var map = new google.maps.Map(document.getElementById('map'));\n map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});\n\n // The marker, now positioned at Pier 39\n var marker = new google.maps.Marker({position: pier39, map: map});\n }\n \u003c/script\u003e\n \u003c!-- Load the API from the specified URL.\n * The async attribute allows the browser to render the page while the API loads.\n * The key parameter will contain your own API key (which is not needed for this tutorial).\n * The callback parameter executes the initMap() function.\n --\u003e\n \u003cscript defer src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap\"\u003e\n \u003c/script\u003e\n \u003c/body\u003e\n \u003c/html\u003e\n\nTo add the JavaScript fleet track library:\n\n1. Add code for the authentication token factory.\n2. Initialize a location provider in the `initMap()` function.\n3. Initialize the map view in the `initMap()` function. The view contains the map.\n4. Move your customization into the callback function for the map view initialization.\n5. Add the location library to the API loader.\n\nMap replacement example using scheduled tasks\n\nThe following examples shows how to use an existing map in which you initialize\nthe location provider object for a scheduled task use case. The code is similar\nfor on-demand trips use cases, except that you use the\n`FleetEngineVehicleLocationProvider` instead of the\n`FleetEngineDeliveryVehicleLocationProvider`. \n\n \u003c!DOCTYPE html\u003e\n \u003chtml\u003e\n \u003chead\u003e\n \u003cstyle\u003e\n /* Set the size of the div element that contains the map */\n #map {\n height: 400px; /* The height is 400 pixels */\n width: 100%; /* The width is the width of the web page */\n }\n \u003c/style\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003ch3\u003eMy Google Maps Demo\u003c/h3\u003e\n \u003c!--The div element for the map --\u003e\n \u003cdiv id=\"map\"\u003e\u003c/div\u003e\n \u003cscript\u003e\n let locationProvider;\n\n // (1) Authentication Token Fetcher\n function authTokenFetcher(options) {\n // options is a record containing two keys called\n // serviceType and context. The developer should\n // generate the correct SERVER_TOKEN_URL and request\n // based on the values of these fields.\n const response = await fetch(SERVER_TOKEN_URL);\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n const data = await response.json();\n return {\n token: data.Token,\n expiresInSeconds: data.ExpiresInSeconds\n };\n }\n\n // Initialize and add the map\n function initMap() {\n // (2) Initialize location provider. Use FleetEngineDeliveryVehicleLocationProvider\n // as appropriate.\n locationProvider = new google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProvider({\n YOUR_PROVIDER_ID,\n authTokenFetcher,\n });\n\n // (3) Initialize map view (which contains the map).\n const mapView = new google.maps.journeySharing.JourneySharingMapView({\n element: document.getElementById('map'),\n locationProviders: [locationProvider],\n // any styling options\n });\n\n mapView.addListener('ready', () =\u003e {\n locationProvider.deliveryVehicleId = DELIVERY_VEHICLE_ID;\n\n // (4) Add customizations like before.\n // The location of Pier 39 in San Francisco\n var pier39 = {lat: 37.809326, lng: -122.409981};\n // The map, initially centered at Mountain View, CA.\n var map = mapView.map;\n map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});\n // The marker, now positioned at Pier 39\n var marker = new google.maps.Marker({position: pier39, map: map});\n };\n }\n \u003c/script\u003e\n \u003c!-- Load the API from the specified URL\n * The async attribute allows the browser to render the page while the API loads\n * The key parameter will contain your own API key (which is not needed for this tutorial)\n * The callback parameter executes the initMap() function\n *\n * (5) Add the journey sharing library to the API loader, which includes Fleet Tracking functionality.\n --\u003e\n \u003cscript defer\n src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing\"\u003e\n \u003c/script\u003e\n \u003c/body\u003e\n \u003c/html\u003e\n\nIf you operate a delivery vehicle with the\nspecified ID near Pier 39, it is now rendered on the map.\n\nWhat's next\n\n- [Customize markers](/maps/documentation/mobility/operations/fleet-tracking/customize-markers)\n- [Customize polylines](/maps/documentation/mobility/operations/fleet-tracking/customize-polylines)"]]