Find a route using Geolocation and Google Maps API

Find a route using Geolocation and Google Maps API

Jul 15, 2018 | HTML, Javascript

Geo-fencing, or geofencing, is a term that refers to software tools or applications that utilize global positioning systems (GPS) or radio frequency identification (RFID) to establish a virtual perimeter or barrier around a physical geographical area.Geo-fence apps and tools monitor when mobile devices or other physical objects enter or exit an established geo-fenced area and provide administrators with alerts when there’s a change in status for a device. These alerts can take the form of text messages, e-mail notifications, phone calls or similar means of communication.

Definition – What does Geolocation mean?

Geolocation is the process of finding, determining and providing the exact location of a computer, networking device or equipment. It enables device location based on geographical coordinates and measurements.

Geolocation commonly uses Global Positioning System (GPS) and other related technologies to assess and specify geographical locations.

HTML codes with file name
index.php

<form id="calculate-route" name="calculate-route" action="#" method="get">
      <label for="from">From:</label>
      <input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
      <a id="from-link" href="#">Get my position</a>
      <br />
 
      <label for="to">To:</label>
      <input type="text" id="to" name="to" required="required" placeholder="Another address" size="30" />
      <a id="to-link" href="#">Get my position</a>
      <br />
 
      <input type="submit" />
      <input type="reset" />
</form>

JavaScripts files codes:

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script>
      function calculateRoute(from, to) {
        // Center initialized to Naples, Italy
        var myOptions = {
          zoom: 10,
          center: new google.maps.LatLng(40.84, 14.25),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // Draw the map
        var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
 
        var directionsService = new google.maps.DirectionsService();
        var directionsRequest = {
          origin: from,
          destination: to,
          travelMode: google.maps.DirectionsTravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.METRIC
        };
        directionsService.route(
          directionsRequest,
          function(response, status)
          {
            if (status == google.maps.DirectionsStatus.OK)
            {
              new google.maps.DirectionsRenderer({
                map: mapObject,
                directions: response
              });
            }
            else
              $("#error").append("Unable to retrieve your route<br />");
          }
        );
      }
 
      $(document).ready(function() {
        // If the browser supports the Geolocation API
        if (typeof navigator.geolocation == "undefined") {
          $("#error").text("Your browser doesn't support the Geolocation API");
          return;
        }
 
        $("#from-link, #to-link").click(function(event) {
          event.preventDefault();
          var addressId = this.id.substring(0, this.id.indexOf("-"));
 
          navigator.geolocation.getCurrentPosition(function(position) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({
              "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
            },
            function(results, status) {
              if (status == google.maps.GeocoderStatus.OK)
                $("#" + addressId).val(results[0].formatted_address);
              else
                $("#error").append("Unable to retrieve your address<br />");
            });
          },
          function(positionError){
            $("#error").append("Error: " + positionError.message + "<br />");
          },
          {
            enableHighAccuracy: true,
            timeout: 10 * 1000 // 10 seconds
          });
        });
 
        $("#calculate-route").submit(function(event) {
          event.preventDefault();
          calculateRoute($("#from").val(), $("#to").val());
        });
      });
</script>
Being Idea is a web platform of programming tutorials to make better programming skills and provides Software Development Solutions.

1 Comment

  1. Being Idea

    Hi,

    Review below code, There you will get object of location details, I have displayed only address from location you can console and get required keys.

    function(results, status) {
    if (status == google.maps.GeocoderStatus.OK)
    $(“#” + addressId).val(results[0].formatted_address);
    else
    $(“#error”).append(“Unable to retrieve your address
    “);
    });

    You must use Google API key for it.

    Reply

Trackbacks/Pingbacks

  1. geoPlugin Web Service interface to find out location information using php | Being Idea - […] learn how to get location, country and zip code using google map API […]

Leave a Reply