GEO Location Track In Google Map With JavaScript


Today, Laravelcode share with you how to track two starting and ending location point in google map with javascript. we are working on one transport related project in laravel and we are required this type starting and ending location point tracking in real time. we have done with javascript.

Google map API provide more API functionality for google map. this tutorials also base one one of the google map API. it related to location tracking.

We are write here some basic step for how to integrate location tracking in very simple way.

Step : 1 Create index.php file

First create one index.php file for show google map and then put into it following code.

<!DOCTYPE html>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
	<script src=""></script>
    <title>Location Track - Laravelcode</title>
		#map {height: 100%;}
		html, body {
			height: 100%;
			margin: 0;
			padding: 0;
		#floating-panel {
			position: absolute;
			top: 10px;
			right: 1%;
			z-index: 5;
			background-color: #fff;
			border: 1px solid #999;
			text-align: center;
    <div id="floating-panel">
    <b>Start1: </b>
    <input tye="text" id="start1" value="Mumbai"><!-- Starting Location -->
    <b>End1: </b>
    <input type="text" id="end1" value="Delhi"><!-- Ending Location -->
    <div id="map"></div>
    <script async defer src=",geometry"></script>

After done this then copy following javascript code and also put into in after map div into script tag


function calcDistance(p1, p2) {//p1 and p2 in the form of google.maps.LatLng object
	return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(3);//distance in KiloMeters

function getLocation() {
	if (navigator.geolocation) {navigator.geolocation.getCurrentPosition(showPosition, showError);} 
	else {alert("Geolocation is not supported by this browser.");}
function showPosition(position) {
	alert("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude); 
function showError(error) {
	switch(error.code) {
			alert("User denied the request for Geolocation.");
			alert("Location information is unavailable.");
		case error.TIMEOUT:
			alert("The request to get user location timed out.");
		case error.UNKNOWN_ERROR:
			alert("An unknown error occurred.");

function initMap() {
	var map = new google.maps.Map(document.getElementById('map'), {
		zoom: 10,
		center: { lat: 18.9965041, lng: 72.8194209 }
	var waypts = [];//origin to destination via waypoints
	//waypts.push({location: 'indore', stopover: true});
	function continuouslyUpdatePosition(location){//Take current location from location.php and set marker to that location
		var xhttp = new XMLHttpRequest();
		xhttp.onreadystatechange = function() {
			if (this.readyState == 4 && this.status == 200) {
				var pos = JSON.parse(this.responseText);
				location.setPosition(new google.maps.LatLng(,pos.lng));
		};"GET", "location.php", true);
	/* Distance between p1 & p2
	var p1 = new google.maps.LatLng(45.463688, 9.18814);
	var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);
	alert(calcDistance(p1,p2)+" Kilimeters");
	//Make marker at any position in form of {lat,lng}
	function makeMarker(position /*, icon*/) {
		var marker = new google.maps.Marker({
			position: position,
			map: map,
			/*animation: google.maps.Animation.DROP,*/
			/*icon: icon,*/
		return marker;
	var icons = {
		end: new google.maps.MarkerImage(''),
		start: new google.maps.MarkerImage('')
	//Show suggestions for places, requires libraries=places in the google maps api script link
	var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('start1'));
	var autocomplete2 = new google.maps.places.Autocomplete(document.getElementById('end1'));
	var directionsService1 = new google.maps.DirectionsService;
	var directionsDisplay1 = new google.maps.DirectionsRenderer({
		polylineOptions: {strokeColor: "red"}, //path color
		//draggable: true,// change start, waypoints and destination by dragging
		/* Start and end marker with same image
		markerOptions : {icon: ''},
		//suppressMarkers: true
	var onChangeHandler1 = function() {calculateAndDisplayRoute(directionsService1, directionsDisplay1, $('#start1'),$('#end1'));};
	function calculateAndDisplayRoute(directionsService, directionsDisplay, start, end) { 
			origin: start.val(),
			destination: end.val(),
			waypoints: waypts,
			travelMode: 'DRIVING'
		}, function(response, status) {
			if (status === 'OK') {
				var leg = response.routes[ 0 ].legs[ 0 ];
				// Move marker along path from A to B
				var markers = [];
				for(var i=0; i<leg.steps.length; i++){
					var marker = makeMarker(leg.steps[i].start_location);
				tracePath(markers, 0);
				var location = makeMarker(leg.steps[0].start_location);
			} else {window.alert('Directions request failed due to ' + status);}
	function tracePath(markers, index){// move marker along path from A to B
		if(index==markers.length)	return;
			tracePath(markers, index+1);
	calculateAndDisplayRoute(directionsService1, directionsDisplay1, $('#start1'),$('#end1'));

Step : 2 Create location.php file

Now, create one location.php file for get all dynamic location from database. we are show here static location but if you want get from database then you make it dynamic

$lat = 23.6838716;
$lng = 73.37194090000003;
echo '{"lat":"'.$lat.'", "lng":"'.$lng.'"}';

If you face any problem then please write a comment or give some suggestions for improvement. Thanks...