Quando você acompanha uma viagem, o app para consumidores mostra a localização do veículo adequado para o consumidor. Para isso, o app precisa começar a acompanhar a viagem, atualizar o progresso durante o trajeto e parar de acompanhar quando ela for concluída.
Este documento aborda as seguintes etapas principais desse processo:
- Configurar um mapa
- Inicializar um mapa e mostrar a viagem compartilhada
- Atualizar e acompanhar o progresso da viagem
- Parar de seguir uma viagem
- Tratar erros de viagem
Configurar um mapa
Para acompanhar a coleta ou entrega de uma remessa no seu web app, carregue um mapa e crie uma instância do SDK do consumidor para começar a rastrear sua jornada. É possível carregar um novo mapa ou usar um já existente. Em seguida, use a função de inicialização para instanciar o SDK do consumidor para que a visualização do mapa corresponda à localização do item rastreado.
Carregar um novo mapa usando a API Google Maps JavaScript
Para criar um mapa, carregue a API Google Maps JavaScript no seu app da Web. O exemplo a seguir mostra como carregar a API Google Maps JavaScript, ativar o SDK e acionar a verificação de inicialização.
- O parâmetro
callback
executa a funçãoinitMap
depois que a API é carregada. - O atributo
defer
permite que o navegador continue renderizando o restante da página enquanto a API é carregada.
Use a função initMap
para instanciar o SDK do consumidor. Exemplo:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>
Carregar um mapa
Também é possível carregar um mapa criado pela API Maps JavaScript, como um que você já esteja usando.
Por exemplo, suponha que você tenha uma página da Web com uma entidade google.maps.Map
padrão em que um marcador é mostrado conforme definido no seguinte código HTML. Isso
mostra seu mapa usando a mesma função initMap
no callback no final:
<!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 defer attribute allows the browser to render the page while the API loads.
* The key parameter contains your own API key.
* 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>
Substituir um mapa
Você pode substituir um mapa que inclui marcadores ou outras personalizações sem perder essas personalizações.
Por exemplo, se você tiver uma página da Web com uma entidade google.maps.Map
padrão em que um marcador é mostrado, poderá substituir o mapa e manter o marcador. Esta seção descreve as etapas para fazer isso.
Para substituir o mapa e manter as personalizações, adicione o compartilhamento de trajeto à sua página HTML seguindo estas etapas, que também estão numeradas no exemplo a seguir:
Adicione o código para a fábrica de tokens de autenticação.
Inicialize um provedor de local na função
initMap()
.Inicialize a visualização do mapa na função
initMap()
. A visualização contém o mapa.Mova sua personalização para a função de callback da inicialização da visualização de mapa.
Adicione a biblioteca de local ao carregador de API.
O exemplo a seguir mostra as mudanças que precisam ser feitas. Se você fizer uma viagem com o ID especificado perto de Uluru, ela vai aparecer no mapa:
<!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
async 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.
locationProvider = new google.maps.journeySharing.FleetEngineTripLocationProvider({
projectId: "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
});
locationProvider.tripId = TRIP_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 = 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
*
* (5) Add the SDK to the API loader.
-->
<script defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
</script>
</body>
</html>
Inicializar um mapa e mostrar o progresso da viagem
Quando uma viagem começa, o app precisa instanciar um provedor de local da viagem e inicializar um mapa para começar a compartilhar o progresso da viagem. Consulte as seções a seguir para exemplos.
Instanciar um provedor de local da viagem
O SDK JavaScript tem um provedor de localização predefinido para a API Fleet Engine Ridesharing. Use o ID do projeto e uma referência à fábrica de tokens para instanciá-la.
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineTripLocationProvider({
projectId: 'your-project-id',
authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step
// Optionally, you may specify a trip ID to
// immediately start tracking.
tripId: 'your-trip-id',
});
TypeScript
locationProvider =
new google.maps.journeySharing
.FleetEngineTripLocationProvider({
projectId: 'your-project-id',
authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step
// Optionally, you may specify a trip ID to
// immediately start tracking.
tripId: 'your-trip-id',
});
Inicializar a visualização de mapa
Depois de carregar o SDK JavaScript, inicialize
a visualização do mapa e adicione-a à página HTML. Sua página precisa conter um elemento <div>
que mantenha a visualização do mapa. O elemento <div>
é chamado de map_canvas
no exemplo a seguir.
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
// Styling customizations; see below.
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-id';
// Give the map an initial viewport to allow it to
// initialize; otherwise, the 'ready' event above may
// not fire. The user also has access to the mapView
// object to customize as they choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);
TypeScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
// Styling customizations; see below.
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-id';
// Give the map an initial viewport to allow it to
// initialize; otherwise, the 'ready' event above may
// not fire. The user also has access to the mapView
// object to customize as they choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);
Atualizar e acompanhar o progresso da viagem
O app precisa detectar eventos e atualizar o progresso da viagem à medida que ela avança. Você pode recuperar metainformações sobre uma viagem do objeto de tarefa usando o provedor de local. As metainformações incluem a ETA e a distância restante antes do embarque ou desembarque. As mudanças nas metainformações acionam um evento de atualização. O exemplo a seguir mostra como detectar esses eventos de mudança.
JavaScript
locationProvider.addListener('update', e => {
// e.trip contains data that may be useful
// to the rest of the UI.
console.log(e.trip.dropOffTime);
});
TypeScript
locationProvider.addListener('update', (e:
google.maps.journeySharing.FleetEngineTripLocationProviderUpdateEvent) => {
// e.trip contains data that may be useful
// to the rest of the UI.
console.log(e.trip.dropOffTime);
});
Parar de seguir uma viagem
Quando a viagem terminar, você precisará interromper o rastreamento do provedor de localização. Para fazer isso, remova o ID da viagem e o provedor de local. Consulte as seções a seguir para exemplos.
Remover o ID da viagem do provedor de localização
O exemplo a seguir mostra como remover um ID de viagem do provedor de local.
JavaScript
locationProvider.tripId = '';
TypeScript
locationProvider.tripId = '';
Remover o provedor de localização da visualização do mapa
O exemplo a seguir mostra como remover um provedor de local da visualização do mapa.
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
Tratar erros de viagem
Erros que surgem de forma assíncrona ao solicitar informações da viagem acionam eventos de erro. O exemplo a seguir mostra como detectar esses eventos para lidar com erros.
JavaScript
locationProvider.addListener('error', e => {
// e.error contains the error that triggered the
// event
console.error(e.error);
});
TypeScript
locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
// e.error contains the error that triggered the
// event
console.error(e.error);
});
A seguir
Personalizar o estilo de um mapa