Link to home
Start Free TrialLog in
Avatar of Swatantra Bhargava
Swatantra BhargavaFlag for India

asked on

Place latitude and longitude on Google Map dynamically on Desktop Application

Dear All,

I have a device (installed on vehicle) which sends latitude and longitude on the Server through GPS. I have a route of that vehicle which is successfully plotted on Google Map.

My Problem is how can I plot latitude and longitude at runtime on Google Map in PHP dynamically on Desktop Application. I want to plot fetched latest latitude and longitude on Google Map to show where the vehicle is running.
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

stop me if I make a mistake.
the vehicle has a gps and you send the gps coordinates to the server
you want to retrieve these coordinates from the server and send them to the desktop application.

Where is the app being run .. on the vehicle on at the office?
Avatar of Swatantra Bhargava

ASKER

No... I am able to retrieve coordinates and I want to place that coordinates on google map. It's easy on mobile Application but I want to do for Desktop Application.
Here to set a marker : https://developers.google.com/maps/documentation/javascript/markers
You just need to download with ajax the lat/long from your server with php :
- query database for all lat/long
- create empty array
- loop over results to fill array
- create json from array
- send back json to browser

check this link : https://www.experts-exchange.com/questions/27074204/Updating-Changing-Coordinates-of-Markers-Live-on-a-Google-Map-from-MySQL-Database.html?anchorAnswerId=35894722#a35894722
Dear Leakim971,

You are not getting my requirement. I have a device which sends latitude and longitude to the Server. I pull these latitudes and longitude from the server and now I want to plot these latitudes and longitude on the Google Map. Dynamic creation of Google map based on fetched latitude and longitude from the Server.

Hope you understood now.
You are not getting my requirement

I believe you did not get my answer...

I pull these latitudes and longitude from the server
do you mean to the server?
can you show the class/module that is causing you grief ?
I can give you an example like UBER, OLA vehicle tacking with LIVE location plotting on google map.
you have the coordinates being passed to your view function.
You say you've created an android app that works. and want to convert that code to work on a desktop application.
all you need to do is create a webbrowser control and have it display in a frame/form on your desktop application.
I want to build a desktop application in PHP which has google maps embedded to it. This app should have a thread to read coordinate data online. This application will move the google map markers to their new locations based on the data retrieved from online connections on each refresh.

Hope you got my requirement.
i know this is an old question, but maybe it can help others.

location.php:
<?php
	/*
		In this file, update lat and lng of the tracked device using GPS module
	*/
	$lat = 23.6838716;
	$lng = 73.37194090000003;
	echo '{"lat":"'.$lat.'", "lng":"'.$lng.'"}';
?>

Open in new window

maps.html:
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <title>Directions service</title>
    <style>
		#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;
		}
    </style>
</head>
<body>
    <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>
    <div id="map"></div>
    <script>
	
	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) {
			case error.PERMISSION_DENIED:
				alert("User denied the request for Geolocation.");
				break;
			case error.POSITION_UNAVAILABLE:
				alert("Location information is unavailable.");
				break;
			case error.TIMEOUT:
				alert("The request to get user location timed out.");
				break;
			case error.UNKNOWN_ERROR:
				alert("An unknown error occurred.");
				break;
		}
	}
	
	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.lat,pos.lng));
					setTimeout(function(){
						continuouslyUpdatePosition(location);
					},5000);
				}
			};
			xhttp.open("GET", "location.php", true);
			xhttp.send();
		}
		
		/* 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('http://icons.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Push-Pin-1-Left-Pink-icon.png'),
			start: new google.maps.MarkerImage('http://icons.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Push-Pin-1-Left-Chartreuse-icon.png')
		};
		
		//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: 'http://icons.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Push-Pin-1-Left-Pink-icon.png'},
			*/
			//suppressMarkers: true
		});
		directionsDisplay1.setMap(map);
		var onChangeHandler1 = function() {calculateAndDisplayRoute(directionsService1, directionsDisplay1, $('#start1'),$('#end1'));};
		$('#start1,#end1').change(onChangeHandler1);		
		
		function calculateAndDisplayRoute(directionsService, directionsDisplay, start, end) { 
			directionsService.route({
				origin: start.val(),
				destination: end.val(),
				waypoints: waypts,
				travelMode: 'DRIVING'
			}, function(response, status) {
				if (status === 'OK') {
					directionsDisplay.setDirections(response);
					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);
						markers.push(marker);
						marker.setMap(null);
					}
					tracePath(markers, 0);
					*/
					var location = makeMarker(leg.steps[0].start_location);
					continuouslyUpdatePosition(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;
			markers[index].setMap(map);
			setTimeout(function(){
				markers[index].setMap(null);
				tracePath(markers, index+1);
			},500);
		}
		
		calculateAndDisplayRoute(directionsService1, directionsDisplay1, $('#start1'),$('#end1'));
	}
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places,geometry"></script>
 </body>
</html>

Open in new window


You will have to use a gps module to get the location and then update latitude and longitude in location.php file.
The maps.html file continuously fetches location from location.php file at intervals of 5 sec and move the marker to that position.
source code from this LINK TO GITHUB
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.