Example 3 – Displaying multiple routes
The following example shows two routes generated by Trip API in the region of Santos, SP.
The variable map
is associated with the class MaplinkMap
and contains the properties of the map, such as div
where it will be initialized. In this case, there is no initial location defined, so the map will be centered automatically when the polyline is obtained in the method line
.
The method map.lines
obtains the latitude/longitude coordinates of the response containing the routes taken by the Trip API with random colors, since it has none defined.
The route responses were defined in the variables tripSolution1
and tripSolution2
and added to the array of the variable routes
.
The map.marker
method adds a marker at the beginning and end. As no icon
has been declared, the default Maplink marker is displayed.
<html> <head> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <script src="https://maps.maplink.global"></script> <style> #map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;} </style> </head> <body> <div id="map"></div> <script type = "text/javascript"> const apiKey = "SUA CHAVE DE API"; const map = new MaplinkMap(apiKey, "map"); const tripSolution1 = JSON.parse(`{ "totalDistance": 367, "legs": [ { "distance": 367, "points": [ { "latitude": -23.983273, "longitude": -46.299793 }, { "latitude": -23.982123, "longitude": -46.299857 }, { "latitude": -23.982008, "longitude": -46.299494 }, { "latitude": -23.982425, "longitude": -46.299191 }, { "latitude": -23.98223, "longitude": -46.298604 }, { "latitude": -23.982033, "longitude": -46.298145 }, { "latitude": -23.981830, "longitude": -46.298312 } ] } ], "source": "MAPLINK" }`); const tripSolution2 = JSON.parse(`{ "totalDistance": 466, "legs": [ { "distance": 466, "points": [ { "latitude": -23.983253, "longitude": -46.296054 }, { "latitude": -23.983809, "longitude": -46.296797 }, { "latitude": -23.983358, "longitude": -46.297131 }, { "latitude": -23.982925, "longitude": -46.297421 }, { "latitude": -23.982033, "longitude": -46.298145 }, { "latitude": -23.981792, "longitude": -46.297682 }, { "latitude": -23.981549, "longitude": -46.297285 }, { "latitude": -23.981672, "longitude": -46.297487 } ] } ], "source": "MAPLINK" }`); const routes = [tripSolution1, tripSolution2].map(trip => trip.legs[0].points); map.lines(routes); for (const route of routes) { map.marker({ latitude: route[0].latitude, longitude: route[0].longitude }); map.marker({ latitude: route[route.length - 1].latitude, longitude: route[route.length - 1].longitude }); } </script> </body> </html>