Logo

How to use Google Map API and HTML 5 to get user's current position (the point A) and draw the direction to (the point B)

Using Google Map API and HTML5, you can get real-time positions and direction between two points. Find out how via this article. To follow this tutorial, you must have basic knowledge of HTML and JavaScript.

Introduction

Do you know how to use the Google MAP API to retrieve a current location? If so, can you also draw a direction from a current user’s location to another location? In case you are wondering how to achieve it, this little tutorial aims to help you achieve it. After reading this article, you will be able to create and obtain a Google API key. Plus, you will understand how to use it in your project to get latitude and longitude. I will provide you with the JavaScript code to get the user’s current position and draw the direction.

1- Obtain the Google Map API key

To get the Google MAP API key, you need a Gmail or G-Suite account. If you don’t have an account, you can create one; it’s free. Once you have created your Gmail or G-Suite account, follow these steps to obtain your API key:

  • Visit https://console.cloud.google.com/ and sign in.
  • The first time you will need to activate your account and add a payment method.
  • You can either click Activate or try it out for free to get started.
  • A form will appear in which you will provide some details about your business.

Note: Google API is not a free service, but in my experience, unless you make too many API requests or calls, you might never have to pay for the service. You can read Google’s terms and conditions for more information.

Google API

Create a Google map API key

If you are successful in activating your account, then you will have access to the Google Cloud Platform dashboard, and then you will do the following:

  • Click on the sandwich menu at the top left (left of the logo).
  • A list will then open, and you can click on API and Services.
  • At the top right of the logo, you will see a drop-down list.
  • If you click on the drop-down list, a window will open, and you can click on the “New project” button to create your project.
  • Then you will need to provide a project name, select a billing account and click “Create.”
  • After you’ve created your new project, by default, it doesn’t contain an API, and you’ll need to click on the library to your left to add APIs.
  • Finally, on the API Library screen, you find Google Map and enable APIs.

There are over 18 APIs, but we only need the Direction API as we will be using the features of HTML 5 to detect the current location.

API Library

Get your API key for your project.

API Key

After selecting the required API, you will need to:

  • Click on “create keys.”
  • Select the API key (the “create keys” action will generate an API key you can use in the next step).
  • Then select “restrict key” (to prevent someone from copying it and using it on their project).
  • You can either restrict with IP or URL.

If your API is for mobile apps, there is an option to restrict Android or iOS apps.

In the API restriction option, you can either leave the option Do not restrict or restrict the key. The “Do not restrict” option will allow you, in some cases, to use the same API on different types of applications. The “Restriction” option only allows you to choose APIs for the type of application you are creating. For example, in our case, we need the API keys for geocoding and steering from Google MAP. Therefore, in the option “restrict key,” we will select.

restrict API

2- Use the JavaScript below to get the current location and direction


<?php 
define("API_KEY","your google map api goes here") ?>
<!DOCTYPE html>
<html>
<head>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 400px;
        width: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
 
    </style> 
</head>
<body>

    <h1>My First Google Map</h1>

    <div id="map"></div>
<input type="hidden" value="120 Rue Louise, Longueuil, QC J4J 2S9" id="end" />
<script>

      function initMap() {

              // Try HTML5 geolocation.
     if (navigator.geolocation) {
            
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
                };

                window.pos = pos; 


        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;
      //  ourOrigin = new google.maps.LatLng(pos.lat, pos.lng);
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: {lat: pos.lat, lng: pos.lng}
        });
        directionsDisplay.setMap(map);

          calculateAndDisplayRoute(directionsService, directionsDisplay);


            });
            } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());
            }



        
       }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {

          console.log("Testing : "+pos);

        directionsService.route({
          origin:  new google.maps.LatLng(pos.lat, pos.lng),
          destination: document.getElementById('end').value,
          travelMode: 'DRIVING'
        }, function(response, status) {
          if (status === 'OK') {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }
    </script>
    
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=<?php echo API_KEY; ?>&callback=initMap">
    </script>



</body>

</html>

Explanation of the code:

Replace your API key in code line 2.

Line 27: Use a form to add a destination and use (See: value = “120 Rue Louise, Longueuil, QC J4J 2S9”). You can change the address as you want.

Lines 35 to 41: We get the current usage information – Latitude and Longitude.

We use the form identifier on line 27 to get the form value on line 73.

References :

  • How to get a current location using the Google Map JavaScript API by phppot.
  • Documentation of the Google Maps platform.

Thanks for reading. You may also be interested in the article “Edit Add to Cart Button with Custom WooCommerce Single Product Page Link.”

Montréal

Our adress

9590 Boul Henri-Bourassa E Bureau 108, Montreal-Est, Quebec H1E 2S4, Canada

Subscribe to receive our news straight to your inbox.