How to calculate Point A to point B with Google Maps
This article will guide you on how to create a form that will show users the directions from Point A (Origin) and Point B (Destination).
It will also create a link that the users can click and open the Google Directions Map and start to navigate using their Desktop or Mobile Devices.
STEPS:
1. Create two Address Autocomplete Fields and name them "Origin" and "Destination"
Important Note
It is required to use Address Autocomplete Field to make it work because those fields will enable the following Google API's which is a pre-requisite for this form- Google Directions API
- Google Maps Javascript API
2. Create a Text Field, name it Link To Map and set the hidden field property to true
3. Create a Header > Free Text Element and put the code below in the source view
<a href="//[Link To Map]" target="_blank">Link to Destination</a>
Note
This will be the field where the actual link will be stored which will be generated by the script4. Create another Header > Free Text Element and put the code below in the source view
<div id="map"> </div>
Note
The <div> with an id of map will be targeted by the google script to generate the actual directions map.
5. Set the Dependencies of the header fields so that it will show only if the Link To Map field is Not Empty
6. Create a new Custom Javascript Action on your form's root node (topmost element) and call it Google Maps Script
GOOGLE MAP SCRIPT:
function initMap() { var directionsService = new google.maps.DirectionsService(); var directionsRenderer = new google.maps.DirectionsRenderer(); var map = new google.maps.Map(document.getElementById('map'), { zoom: 7, center: { lat: 41.85, lng: -87.65 } }); directionsRenderer.setMap(map); var onChangeHandler = function() { calculateAndDisplayRoute(directionsService, directionsRenderer); }; lfform.getFieldByName("Origin").el[0].addEventListener('change', onChangeHandler); lfform.getFieldByName("Destination").el[0].addEventListener('change', onChangeHandler); } function calculateAndDisplayRoute(directionsService, directionsRenderer) { directionsService.route({ origin: { query: lfform.getFieldByName("Origin").el[0].value }, destination: { query: lfform.getFieldByName("Destination").el[0].value }, travelMode: 'DRIVING' }, function(response, status) { if (status === 'OK') { directionsRenderer.setDirections(response); var originValue = lfform.getFieldByName("Origin").getValue(); var destinationValue = lfform.getFieldByName("Destination").getValue(); var linkToMapField = lfform.getFieldByName("Link To Map"); var linkToMapFieldId = linkToMapField.id; lfform.getFieldByName("Link To Map").setValue(`www.google.com/maps/dir/${originValue}/${destinationValue}`) lfform.triggerFieldEvent(linkToMapFieldId,null,true); } else { window.alert('Directions request failed due to ' + status); } }); }
0 Comments