Geofencing Add Marker and Fetch data from database
Maps.js
jQuery(document).ready(function($) {
'use strict';
var map = document.getElementById('map-canvas');
var routeSelect = document.getElementById('routeSelect');
var viewingAllRoutes = false;
var sessionIDArray = [];
var intervalID = 0;
var dynaradius= 0;
getAllRoutesForMap();
loadRoutesIntoDropdownBox()
$("#routeSelect").change(function() {
if (hasMap()) {
viewingAllRoutes = false;
getRouteForMap();
}
});
$("#edit").click(function() {
editRoute();
});
$("#radius").focusout(function(){
//dynaradius = document.getElementById("radius").value;
//getRouteForMap();
});
function getAllRoutesForMap() {
viewingAllRoutes = true;
routeSelect.selectedIndex = 0;
$.ajax({
url: 'getallroutesformap.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log("Remote"+data);
loadGPSLocations(data);
},
error: function (xhr, status, errorThrown) {
console.log("error status: " + xhr.status);
//console.log("errorThrown: " + errorThrown);
}
});
}
function loadRoutesIntoDropdownBox() {
$.ajax({
url: 'getroutes.php',
type: 'GET',
dataType: 'json',
success: function(data) {
loadRoutes(data);
},
error: function (xhr, status, errorThrown) {
console.log("status: " + xhr.status);
//console.log("errorThrown: " + errorThrown);
}
});
}
function getRouteForMap() {
viewingAllRoutes = false;
console.log($("#routeSelect").prop("selectedIndex"));
var url = 'getrouteformap.php' + $('#routeSelect').val();
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin':'*',
},
success: function(data) {
loadGPSLocations(data);
},
error: function (xhr, status, errorThrown) {
console.log("status: " + xhr.status);
console.log("errorThrown: " + errorThrown);
}
});
}
function loadGPSLocations(json) {
console.log(JSON.stringify(json));
if (json.length == 0) {
}
else {
if (map.id == 'map-canvas') {
document.getElementById('map-canvas').outerHTML = "<div id='map-canvas'></div>";
var gpsTrackerMap = new L.map('map-canvas');
var openStreetMapsURL = ('https:' == document.location.protocol ? 'https://' : 'http://') +'{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var openStreetMapsLayer = new L.TileLayer(openStreetMapsURL,{attribution:'©2014 <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'});
var googleMapsLayer = new L.Google('ROADMAP');
L.polyline([[0, 0], ]).addTo(gpsTrackerMap);
gpsTrackerMap.addLayer(googleMapsLayer);
gpsTrackerMap.addControl(new L.Control.Layers({
// 'Bing Maps':bingMapsLayer,
'Google Maps':googleMapsLayer,
'OpenStreetMaps':openStreetMapsLayer
}, {}));
}
var finalLocation = false;
var counter = 0;
var locationArray = [];
$(json.locations).each(function(key, value){
var latitude = $(this).attr('latitude');
var longitude = $(this).attr('longitude');
var latlng= latitude+","+longitude;
var tempLocation = new L.LatLng(latitude, longitude);
locationArray.push(tempLocation);
counter++;
if (counter == $(json.locations).length) {
finalLocation = true;
if (!viewingAllRoutes) {
displayCityName(latitude, longitude);
}
}
var singleroute = $(json.locations).length;
if(singleroute =="1"){
$("#latlng").val(latlng);
$("#devicid").val($(this).attr('userName'));
$("#radius").val($(this).attr('accuracy'));
$("#inform").val("meter");
}
var marker = createMarker(
latitude,
longitude,
$(this).attr('speed'),
$(this).attr('direction'),
$(this).attr('distance'),
$(this).attr('locationMethod'),
$(this).attr('gpsTime'),
$(this).attr('userName'),
$(this).attr('sessionID'),
$(this).attr('accuracy'),
$(this).attr('extraInfo'),
gpsTrackerMap, finalLocation);
});
var bounds = new L.LatLngBounds(locationArray);
gpsTrackerMap.fitBounds(bounds);
}
turnOnAutoRefresh();
}
function loadRoutes(json) {
if (json.length == 0) {
}
else {
var option = document.createElement('option');
option.setAttribute('value', '0');
option.innerHTML = 'Select Route...';
routeSelect.appendChild(option);
sessionIDArray = [];
$(json.routes).each(function(key, value){
var option = document.createElement('option');
option.setAttribute('value', '?sessionid=' + $(this).attr('sessionID'));
sessionIDArray.push($(this).attr('sessionID'));
option.innerHTML = $(this).attr('userName') + " " + $(this).attr('times');
routeSelect.appendChild(option);
})
routeSelect.selectedIndex = 0;
}
}
function displayCityName(latitude, longitude) {
var lat = parseFloat(latitude);
var lng = parseFloat(longitude);
var latlng = new google.maps.LatLng(lat, lng);
var reverseGeocoder = new google.maps.Geocoder();
reverseGeocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var reverseGeocoderResult = results[1].formatted_address;
console.log('Geocoder Address: ' + reverseGeocoderResult);
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function createMarker(latitude, longitude, speed, direction, distance, locationMethod, gpsTime,userName, sessionID, accuracy, extraInfo, map, finalLocation) {
var iconUrl;
if (finalLocation) {
iconUrl = 'images/coolred_small.png';
} else {
iconUrl = 'images/coolgreen2_small.png';
}
var markerIcon = new L.Icon({
iconUrl: iconUrl,
shadowUrl: 'images/coolshadow_small.png',
iconSize: [12, 20],
shadowSize: [22, 20],
iconAnchor: [6, 20],
shadowAnchor: [6, 20],
popupAnchor: [-3, -25]
});
// if(dynaradius!=0){
// accuracy = dynaradius;
// }
var mcircle = new L.circle(new L.LatLng(latitude, longitude),accuracy,{
color: 'blue',
fillColor: extraInfo,
fillOpacity: 0.5,
});
var lastMarker = "</td></tr>";
if (finalLocation) {
lastMarker = "</td></tr><tr><td align=left> </td><td><b>Final location</b></td></tr>";
}
accuracy = parseInt(accuracy * 3.28);
var popupWindowText = "<table border=0 style=\"font-size:95%;font-family:arial,helvetica,sans-serif;color:#000;\">" +
"<tr><td align=right> </td><td> </td><td rowspan=2 align=right>" +
"<img src=images/" + getCompassImage(direction) + ".jpg alt= />" + lastMarker +
"<tr><td align=right>Speed: </td><td>" + speed + " mph</td></tr>" +
"<tr><td align=right>Distance: </td><td>" + distance + " mi</td><td> </td></tr>" +
"<tr><td align=right>Time: </td><td colspan=2>" + gpsTime + "</td></tr>" +
"<tr><td align=right>Name: </td><td>" + userName + "</td><td> </td></tr>" +
"<tr><td align=right>Accuracy: </td><td>" + accuracy + " ft</td><td> </td></tr></table>";
var gpstrackerMarker;
var gpstrackCircle;
var title ="Demo";
var fillColor="*";
if (finalLocation) {
gpstrackCircle = mcircle.addTo(map);
gpstrackerMarker = new L.marker(new L.LatLng(latitude, longitude), {title: title, icon: markerIcon, zIndexOffset: 999}).bindPopup(popupWindowText).addTo(map);
} else {
gpstrackCircle = mcircle.addTo(map);
gpstrackerMarker = new L.marker(new L.LatLng(latitude, longitude), {title: title, icon: markerIcon}).bindPopup(popupWindowText).addTo(map);
}
}
function getCompassImage(azimuth) {
if ((azimuth >= 337 && azimuth <= 360) || (azimuth >= 0 && azimuth < 23))
return "compassN";
if (azimuth >= 23 && azimuth < 68)
return "compassNE";
if (azimuth >= 68 && azimuth < 113)
return "compassE";
if (azimuth >= 113 && azimuth < 158)
return "compassSE";
if (azimuth >= 158 && azimuth < 203)
return "compassS";
if (azimuth >= 203 && azimuth < 248)
return "compassSW";
if (azimuth >= 248 && azimuth < 293)
return "compassW";
if (azimuth >= 293 && azimuth < 337)
return "compassNW";
return "";
}
function hasMap() {
if (routeSelect.selectedIndex == 0) { // means no map
return false;
}
else {
return true;
}
}
function editRoute() {
var rradius = document.getElementById("radius").value;
if (hasMap()) {
var url = 'EditRoute' + $('#routeSelect').val() +","+ rradius;
console.log("url"+url);
$.ajax({
url: url,
type: 'GET',
success: function(data) {
getRouteForMap();
}
});
}
else {
alert("Please select a route before trying to delete.");
}
}
function turnOnAutoRefresh() {
if (viewingAllRoutes) {
alert("ALLROUTES");
intervalID = setInterval(getAllRoutesForMap, 60 * 1000); // one minute
} else {
alert("ONEROUTES");
// intervalID = setInterval(getRouteForMap, 60 * 1000);
}
}
});
dbconnected.php
<?php
const DB_MYSQL = 0;
const DB_POSTGRESQL = 1;
const DB_SQLITE3 = 2;
// ======== Start of user-configurable variables =======================
// --- set this to use YOUR database type: ------
$dbType = DB_MYSQL;
// if your database is DB_SQLITE3, you need to set the path to your database file:
$pathToSQLite = 'sqlite\gpstracker.sqlite';
// ======== End of user-configurable variables =======================
$dbuser = 'root';
$dbpass = '';
$params = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
switch ($dbType) {
case DB_MYSQL:
$pdo = new PDO('mysql:host=localhost;dbname=php_gps;charset=utf8', $dbuser, $dbpass, $params);
$sqlFunctionCallMethod = 'CALL ';
break;
}
?>
Displaymap.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<title>Gps Tracker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- <script src="//maps.googleapis.com/maps/api/js?key=AIzaSyDudFyTGhbU2CvJtJNxdfkPcJfRQnZ1pbTg&libraries=geometry"></script> -->
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyDPj5ClObVWPZ8WJxxl8v5HRaZSniDz2gg&libraries=geometry"></script>
<script src="js/maps.js"></script>
<script src="js/leaflet-0.7.5/leaflet.js"></script>
<script src="js/leaflet-plugins/google.js"></script>
<script src="js/leaflet-plugins/bing.js"></script>
<link rel="stylesheet" href="js/leaflet-0.7.5/leaflet.css">
<!--
to change themes, select a theme here: http://www.bootstrapcdn.com/#bootswatch_tab
and then change the word after 3.2.0 in the following link to the new theme name
-->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cerulean/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="container-fluid">
<!-- -->
<div class="row">
<div class="col-sm-4" id="toplogo">
<img id="halimage" src="images/gpstracker-man-blue-37.png">GeoFence Tracker
</div>
<div class="col-sm-4" id="messages"></div>
<div class="col-sm-4" style="text-align:right;margin-top:2px;">
<a href="../Geofencing_new/index.php" class="btn btn-danger btn-flat">Sign out</a>
</div>
</div>
<!-- -->
<!-- -->
<div class="row">
<div class="col-sm-12" id="mapdiv">
<div id="map-canvas"></div>
</div>
</div>
<!-- -->
<!-- -->
<div class="row">
<div class="col-sm-12" id="selectdiv">
<select id="routeSelect" tabindex="1"></select>
</div>
</div>
<!-- -->
<div class="row">
</div>
</div>
<!-- -->
<!-- -->
<!-- -->
</div>
<div class="container-fluid" bgcolor="#ef0211">
<br>
<div class="form-group col-lg-2">
<input type="text" class="form-control" id="latlng" value="" placeholder="Lat,Long">
</div>
<div class="form-group col-lg-2">
<input type="text" class="form-control" id="devicid" value="" placeholder="DevicName/id">
</div>
<div class="form-group col-lg-2">
<input type="text" class="form-control" id="radius" value="" placeholder="Radius">
</div>
<div class="form-group col-lg-2">
<input type="text" class="form-control" id="inform" value="" placeholder="meter">
</div>
<div class="form-group col-lg-2">
<button type="button" class="btn btn-primary" id="edit">EDIT</button>
</div>
<div class="form-group col-lg-1">
<button type="button" class="btn btn-danger" id="delete">DELETE</button>
</div>
</div>
</body>
</html>
<?php
include 'dbconnect.php';
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare('CALL prcGetAllRoutesForMap();');
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare('select * from v_GetAllRoutesForMap;');
break;
}
$stmt->execute();
$json = '{ "locations": [';
foreach ($stmt as $row) {
$json .= $row['json'];
$json .= ',';
}
$json = rtrim($json, ",");
$json .= '] }';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo $json;
?>
getallroutesformap.php
<?php
include 'dbconnect.php';
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare('CALL prcGetAllRoutesForMap();');
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare('select * from v_GetAllRoutesForMap;');
break;
}
$stmt->execute();
$json = '{ "locations": [';
foreach ($stmt as $row) {
$json .= $row['json'];
$json .= ',';
}
$json = rtrim($json, ",");
$json .= '] }';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo $json;
?>
getrouteformap:-
<?php
include 'dbconnect.php';
$sessionid = isset($_GET['sessionid']) ? $_GET['sessionid'] : '0';
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare('CALL prcGetRouteForMap(:sessionID)');
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare("select * from v_GetRouteForMap where sessionID = :sessionID");
break;
}
$stmt->execute(array(':sessionID' => $sessionid));
$json = '{ "locations": [';
foreach ($stmt as $row) {
$json .= $row['json'];
$json .= ',';
}
$json = rtrim($json, ",");
$json .= '] }';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo $json;
?>
getroutes:-
<?php
include 'dbconnect.php';
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare('CALL prcGetRoutes();');
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare('select * from v_GetRoutes;');
break;
}
$stmt->execute();
$json = '{ "routes": [';
foreach ($stmt as $row) {
$json .= $row['json'];
$json .= ',';
}
$json = rtrim($json, ",");
$json .= '] }';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo $json;
?>
updatelocation:-
<?php
include 'dbconnect.php';
$latitude = isset($_GET['latitude']) ? $_GET['latitude'] : '0';
$latitude = (float)str_replace(",", ".", $latitude); // to handle European locale decimals
$longitude = isset($_GET['longitude']) ? $_GET['longitude'] : '0';
$longitude = (float)str_replace(",", ".", $longitude);
$speed = isset($_GET['speed']) ? $_GET['speed'] : 0;
$direction = isset($_GET['direction']) ? $_GET['direction'] : 0;
$distance = isset($_GET['distance']) ? $_GET['distance'] : '0';
$distance = (float)str_replace(",", ".", $distance);
$date = isset($_GET['date']) ? $_GET['date'] : '0000-00-00 00:00:00';
$date = urldecode($date);
$locationmethod = isset($_GET['locationmethod']) ? $_GET['locationmethod'] : '';
$locationmethod = urldecode($locationmethod);
$username = isset($_GET['username']) ? $_GET['username'] : 0;
$phonenumber = isset($_GET['phonenumber']) ? $_GET['phonenumber'] : '';
$sessionid = isset($_GET['sessionid']) ? $_GET['sessionid'] : 0;
$accuracy = isset($_GET['accuracy']) ? $_GET['accuracy'] : 0;
$extrainfo = isset($_GET['extrainfo']) ? $_GET['extrainfo'] : '';
$eventtype = isset($_GET['eventtype']) ? $_GET['eventtype'] : '';
// doing some validation here
if ($latitude == 0 && $longitude == 0) {
exit('-1');
}
$params = array(':latitude' => $latitude,
':longitude' => $longitude,
':speed' => $speed,
':direction' => $direction,
':distance' => $distance,
':date' => $date,
':locationmethod' => $locationmethod,
':username' => $username,
':phonenumber' => $phonenumber,
':sessionid' => $sessionid,
':accuracy' => $accuracy,
':extrainfo' => $extrainfo,
':eventtype' => $eventtype
);
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare( $sqlFunctionCallMethod.'prcSaveGPSLocation(
:latitude,
:longitude,
:speed,
:direction,
:distance,
:date,
:locationmethod,
:username,
:phonenumber,
:sessionid,
:accuracy,
:extrainfo,
:eventtype);'
);
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare('INSERT INTO gpslocations (latitude, longitude, speed, direction, distance, gpsTime, locationMethod, userName, phoneNumber, sessionID, accuracy, extraInfo, eventType) VALUES (:latitude, :longitude, :speed, :direction, :distance, :date, :locationmethod, :username, :phonenumber, :sessionid, :accuracy, :extrainfo, :eventtype)');
break;
}
$stmt->execute($params);
$timestamp = $stmt->fetchColumn();
echo $timestamp;
?>
jQuery(document).ready(function($) {
'use strict';
var map = document.getElementById('map-canvas');
var routeSelect = document.getElementById('routeSelect');
var viewingAllRoutes = false;
var sessionIDArray = [];
var intervalID = 0;
var dynaradius= 0;
getAllRoutesForMap();
loadRoutesIntoDropdownBox()
$("#routeSelect").change(function() {
if (hasMap()) {
viewingAllRoutes = false;
getRouteForMap();
}
});
$("#edit").click(function() {
editRoute();
});
$("#radius").focusout(function(){
//dynaradius = document.getElementById("radius").value;
//getRouteForMap();
});
function getAllRoutesForMap() {
viewingAllRoutes = true;
routeSelect.selectedIndex = 0;
$.ajax({
url: 'getallroutesformap.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log("Remote"+data);
loadGPSLocations(data);
},
error: function (xhr, status, errorThrown) {
console.log("error status: " + xhr.status);
//console.log("errorThrown: " + errorThrown);
}
});
}
function loadRoutesIntoDropdownBox() {
$.ajax({
url: 'getroutes.php',
type: 'GET',
dataType: 'json',
success: function(data) {
loadRoutes(data);
},
error: function (xhr, status, errorThrown) {
console.log("status: " + xhr.status);
//console.log("errorThrown: " + errorThrown);
}
});
}
function getRouteForMap() {
viewingAllRoutes = false;
console.log($("#routeSelect").prop("selectedIndex"));
var url = 'getrouteformap.php' + $('#routeSelect').val();
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin':'*',
},
success: function(data) {
loadGPSLocations(data);
},
error: function (xhr, status, errorThrown) {
console.log("status: " + xhr.status);
console.log("errorThrown: " + errorThrown);
}
});
}
function loadGPSLocations(json) {
console.log(JSON.stringify(json));
if (json.length == 0) {
}
else {
if (map.id == 'map-canvas') {
document.getElementById('map-canvas').outerHTML = "<div id='map-canvas'></div>";
var gpsTrackerMap = new L.map('map-canvas');
var openStreetMapsURL = ('https:' == document.location.protocol ? 'https://' : 'http://') +'{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var openStreetMapsLayer = new L.TileLayer(openStreetMapsURL,{attribution:'©2014 <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'});
var googleMapsLayer = new L.Google('ROADMAP');
L.polyline([[0, 0], ]).addTo(gpsTrackerMap);
gpsTrackerMap.addLayer(googleMapsLayer);
gpsTrackerMap.addControl(new L.Control.Layers({
// 'Bing Maps':bingMapsLayer,
'Google Maps':googleMapsLayer,
'OpenStreetMaps':openStreetMapsLayer
}, {}));
}
var finalLocation = false;
var counter = 0;
var locationArray = [];
$(json.locations).each(function(key, value){
var latitude = $(this).attr('latitude');
var longitude = $(this).attr('longitude');
var latlng= latitude+","+longitude;
var tempLocation = new L.LatLng(latitude, longitude);
locationArray.push(tempLocation);
counter++;
if (counter == $(json.locations).length) {
finalLocation = true;
if (!viewingAllRoutes) {
displayCityName(latitude, longitude);
}
}
var singleroute = $(json.locations).length;
if(singleroute =="1"){
$("#latlng").val(latlng);
$("#devicid").val($(this).attr('userName'));
$("#radius").val($(this).attr('accuracy'));
$("#inform").val("meter");
}
var marker = createMarker(
latitude,
longitude,
$(this).attr('speed'),
$(this).attr('direction'),
$(this).attr('distance'),
$(this).attr('locationMethod'),
$(this).attr('gpsTime'),
$(this).attr('userName'),
$(this).attr('sessionID'),
$(this).attr('accuracy'),
$(this).attr('extraInfo'),
gpsTrackerMap, finalLocation);
});
var bounds = new L.LatLngBounds(locationArray);
gpsTrackerMap.fitBounds(bounds);
}
turnOnAutoRefresh();
}
function loadRoutes(json) {
if (json.length == 0) {
}
else {
var option = document.createElement('option');
option.setAttribute('value', '0');
option.innerHTML = 'Select Route...';
routeSelect.appendChild(option);
sessionIDArray = [];
$(json.routes).each(function(key, value){
var option = document.createElement('option');
option.setAttribute('value', '?sessionid=' + $(this).attr('sessionID'));
sessionIDArray.push($(this).attr('sessionID'));
option.innerHTML = $(this).attr('userName') + " " + $(this).attr('times');
routeSelect.appendChild(option);
})
routeSelect.selectedIndex = 0;
}
}
function displayCityName(latitude, longitude) {
var lat = parseFloat(latitude);
var lng = parseFloat(longitude);
var latlng = new google.maps.LatLng(lat, lng);
var reverseGeocoder = new google.maps.Geocoder();
reverseGeocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var reverseGeocoderResult = results[1].formatted_address;
console.log('Geocoder Address: ' + reverseGeocoderResult);
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function createMarker(latitude, longitude, speed, direction, distance, locationMethod, gpsTime,userName, sessionID, accuracy, extraInfo, map, finalLocation) {
var iconUrl;
if (finalLocation) {
iconUrl = 'images/coolred_small.png';
} else {
iconUrl = 'images/coolgreen2_small.png';
}
var markerIcon = new L.Icon({
iconUrl: iconUrl,
shadowUrl: 'images/coolshadow_small.png',
iconSize: [12, 20],
shadowSize: [22, 20],
iconAnchor: [6, 20],
shadowAnchor: [6, 20],
popupAnchor: [-3, -25]
});
// if(dynaradius!=0){
// accuracy = dynaradius;
// }
var mcircle = new L.circle(new L.LatLng(latitude, longitude),accuracy,{
color: 'blue',
fillColor: extraInfo,
fillOpacity: 0.5,
});
var lastMarker = "</td></tr>";
if (finalLocation) {
lastMarker = "</td></tr><tr><td align=left> </td><td><b>Final location</b></td></tr>";
}
accuracy = parseInt(accuracy * 3.28);
var popupWindowText = "<table border=0 style=\"font-size:95%;font-family:arial,helvetica,sans-serif;color:#000;\">" +
"<tr><td align=right> </td><td> </td><td rowspan=2 align=right>" +
"<img src=images/" + getCompassImage(direction) + ".jpg alt= />" + lastMarker +
"<tr><td align=right>Speed: </td><td>" + speed + " mph</td></tr>" +
"<tr><td align=right>Distance: </td><td>" + distance + " mi</td><td> </td></tr>" +
"<tr><td align=right>Time: </td><td colspan=2>" + gpsTime + "</td></tr>" +
"<tr><td align=right>Name: </td><td>" + userName + "</td><td> </td></tr>" +
"<tr><td align=right>Accuracy: </td><td>" + accuracy + " ft</td><td> </td></tr></table>";
var gpstrackerMarker;
var gpstrackCircle;
var title ="Demo";
var fillColor="*";
if (finalLocation) {
gpstrackCircle = mcircle.addTo(map);
gpstrackerMarker = new L.marker(new L.LatLng(latitude, longitude), {title: title, icon: markerIcon, zIndexOffset: 999}).bindPopup(popupWindowText).addTo(map);
} else {
gpstrackCircle = mcircle.addTo(map);
gpstrackerMarker = new L.marker(new L.LatLng(latitude, longitude), {title: title, icon: markerIcon}).bindPopup(popupWindowText).addTo(map);
}
}
function getCompassImage(azimuth) {
if ((azimuth >= 337 && azimuth <= 360) || (azimuth >= 0 && azimuth < 23))
return "compassN";
if (azimuth >= 23 && azimuth < 68)
return "compassNE";
if (azimuth >= 68 && azimuth < 113)
return "compassE";
if (azimuth >= 113 && azimuth < 158)
return "compassSE";
if (azimuth >= 158 && azimuth < 203)
return "compassS";
if (azimuth >= 203 && azimuth < 248)
return "compassSW";
if (azimuth >= 248 && azimuth < 293)
return "compassW";
if (azimuth >= 293 && azimuth < 337)
return "compassNW";
return "";
}
function hasMap() {
if (routeSelect.selectedIndex == 0) { // means no map
return false;
}
else {
return true;
}
}
function editRoute() {
var rradius = document.getElementById("radius").value;
if (hasMap()) {
var url = 'EditRoute' + $('#routeSelect').val() +","+ rradius;
console.log("url"+url);
$.ajax({
url: url,
type: 'GET',
success: function(data) {
getRouteForMap();
}
});
}
else {
alert("Please select a route before trying to delete.");
}
}
function turnOnAutoRefresh() {
if (viewingAllRoutes) {
alert("ALLROUTES");
intervalID = setInterval(getAllRoutesForMap, 60 * 1000); // one minute
} else {
alert("ONEROUTES");
// intervalID = setInterval(getRouteForMap, 60 * 1000);
}
}
});
dbconnected.php
<?php
const DB_MYSQL = 0;
const DB_POSTGRESQL = 1;
const DB_SQLITE3 = 2;
// ======== Start of user-configurable variables =======================
// --- set this to use YOUR database type: ------
$dbType = DB_MYSQL;
// if your database is DB_SQLITE3, you need to set the path to your database file:
$pathToSQLite = 'sqlite\gpstracker.sqlite';
// ======== End of user-configurable variables =======================
$dbuser = 'root';
$dbpass = '';
$params = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
switch ($dbType) {
case DB_MYSQL:
$pdo = new PDO('mysql:host=localhost;dbname=php_gps;charset=utf8', $dbuser, $dbpass, $params);
$sqlFunctionCallMethod = 'CALL ';
break;
}
?>
Displaymap.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<title>Gps Tracker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- <script src="//maps.googleapis.com/maps/api/js?key=AIzaSyDudFyTGhbU2CvJtJNxdfkPcJfRQnZ1pbTg&libraries=geometry"></script> -->
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyDPj5ClObVWPZ8WJxxl8v5HRaZSniDz2gg&libraries=geometry"></script>
<script src="js/maps.js"></script>
<script src="js/leaflet-0.7.5/leaflet.js"></script>
<script src="js/leaflet-plugins/google.js"></script>
<script src="js/leaflet-plugins/bing.js"></script>
<link rel="stylesheet" href="js/leaflet-0.7.5/leaflet.css">
<!--
to change themes, select a theme here: http://www.bootstrapcdn.com/#bootswatch_tab
and then change the word after 3.2.0 in the following link to the new theme name
-->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cerulean/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="container-fluid">
<!-- -->
<div class="row">
<div class="col-sm-4" id="toplogo">
<img id="halimage" src="images/gpstracker-man-blue-37.png">GeoFence Tracker
</div>
<div class="col-sm-4" id="messages"></div>
<div class="col-sm-4" style="text-align:right;margin-top:2px;">
<a href="../Geofencing_new/index.php" class="btn btn-danger btn-flat">Sign out</a>
</div>
</div>
<!-- -->
<!-- -->
<div class="row">
<div class="col-sm-12" id="mapdiv">
<div id="map-canvas"></div>
</div>
</div>
<!-- -->
<!-- -->
<div class="row">
<div class="col-sm-12" id="selectdiv">
<select id="routeSelect" tabindex="1"></select>
</div>
</div>
<!-- -->
<div class="row">
</div>
</div>
<!-- -->
<!-- -->
<!-- -->
</div>
<div class="container-fluid" bgcolor="#ef0211">
<br>
<div class="form-group col-lg-2">
<input type="text" class="form-control" id="latlng" value="" placeholder="Lat,Long">
</div>
<div class="form-group col-lg-2">
<input type="text" class="form-control" id="devicid" value="" placeholder="DevicName/id">
</div>
<div class="form-group col-lg-2">
<input type="text" class="form-control" id="radius" value="" placeholder="Radius">
</div>
<div class="form-group col-lg-2">
<input type="text" class="form-control" id="inform" value="" placeholder="meter">
</div>
<div class="form-group col-lg-2">
<button type="button" class="btn btn-primary" id="edit">EDIT</button>
</div>
<div class="form-group col-lg-1">
<button type="button" class="btn btn-danger" id="delete">DELETE</button>
</div>
</div>
</body>
</html>
<?php
include 'dbconnect.php';
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare('CALL prcGetAllRoutesForMap();');
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare('select * from v_GetAllRoutesForMap;');
break;
}
$stmt->execute();
$json = '{ "locations": [';
foreach ($stmt as $row) {
$json .= $row['json'];
$json .= ',';
}
$json = rtrim($json, ",");
$json .= '] }';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo $json;
?>
getallroutesformap.php
<?php
include 'dbconnect.php';
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare('CALL prcGetAllRoutesForMap();');
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare('select * from v_GetAllRoutesForMap;');
break;
}
$stmt->execute();
$json = '{ "locations": [';
foreach ($stmt as $row) {
$json .= $row['json'];
$json .= ',';
}
$json = rtrim($json, ",");
$json .= '] }';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo $json;
?>
getrouteformap:-
<?php
include 'dbconnect.php';
$sessionid = isset($_GET['sessionid']) ? $_GET['sessionid'] : '0';
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare('CALL prcGetRouteForMap(:sessionID)');
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare("select * from v_GetRouteForMap where sessionID = :sessionID");
break;
}
$stmt->execute(array(':sessionID' => $sessionid));
$json = '{ "locations": [';
foreach ($stmt as $row) {
$json .= $row['json'];
$json .= ',';
}
$json = rtrim($json, ",");
$json .= '] }';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo $json;
?>
getroutes:-
<?php
include 'dbconnect.php';
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare('CALL prcGetRoutes();');
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare('select * from v_GetRoutes;');
break;
}
$stmt->execute();
$json = '{ "routes": [';
foreach ($stmt as $row) {
$json .= $row['json'];
$json .= ',';
}
$json = rtrim($json, ",");
$json .= '] }';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo $json;
?>
updatelocation:-
<?php
include 'dbconnect.php';
$latitude = isset($_GET['latitude']) ? $_GET['latitude'] : '0';
$latitude = (float)str_replace(",", ".", $latitude); // to handle European locale decimals
$longitude = isset($_GET['longitude']) ? $_GET['longitude'] : '0';
$longitude = (float)str_replace(",", ".", $longitude);
$speed = isset($_GET['speed']) ? $_GET['speed'] : 0;
$direction = isset($_GET['direction']) ? $_GET['direction'] : 0;
$distance = isset($_GET['distance']) ? $_GET['distance'] : '0';
$distance = (float)str_replace(",", ".", $distance);
$date = isset($_GET['date']) ? $_GET['date'] : '0000-00-00 00:00:00';
$date = urldecode($date);
$locationmethod = isset($_GET['locationmethod']) ? $_GET['locationmethod'] : '';
$locationmethod = urldecode($locationmethod);
$username = isset($_GET['username']) ? $_GET['username'] : 0;
$phonenumber = isset($_GET['phonenumber']) ? $_GET['phonenumber'] : '';
$sessionid = isset($_GET['sessionid']) ? $_GET['sessionid'] : 0;
$accuracy = isset($_GET['accuracy']) ? $_GET['accuracy'] : 0;
$extrainfo = isset($_GET['extrainfo']) ? $_GET['extrainfo'] : '';
$eventtype = isset($_GET['eventtype']) ? $_GET['eventtype'] : '';
// doing some validation here
if ($latitude == 0 && $longitude == 0) {
exit('-1');
}
$params = array(':latitude' => $latitude,
':longitude' => $longitude,
':speed' => $speed,
':direction' => $direction,
':distance' => $distance,
':date' => $date,
':locationmethod' => $locationmethod,
':username' => $username,
':phonenumber' => $phonenumber,
':sessionid' => $sessionid,
':accuracy' => $accuracy,
':extrainfo' => $extrainfo,
':eventtype' => $eventtype
);
switch ($dbType) {
case DB_MYSQL:
$stmt = $pdo->prepare( $sqlFunctionCallMethod.'prcSaveGPSLocation(
:latitude,
:longitude,
:speed,
:direction,
:distance,
:date,
:locationmethod,
:username,
:phonenumber,
:sessionid,
:accuracy,
:extrainfo,
:eventtype);'
);
break;
case DB_POSTGRESQL:
case DB_SQLITE3:
$stmt = $pdo->prepare('INSERT INTO gpslocations (latitude, longitude, speed, direction, distance, gpsTime, locationMethod, userName, phoneNumber, sessionID, accuracy, extraInfo, eventType) VALUES (:latitude, :longitude, :speed, :direction, :distance, :date, :locationmethod, :username, :phonenumber, :sessionid, :accuracy, :extrainfo, :eventtype)');
break;
}
$stmt->execute($params);
$timestamp = $stmt->fetchColumn();
echo $timestamp;
?>
lat_long:-
<?php
$sql_mode = '1';
$sql_host = 'localhost';
$sql_user = "root";
$sql_pass = "";
$sql_data = "";
// Opens a connection to a MySQL server
$connection=mysql_connect ($sql_host, $sql_user,$sql_pass);
if (!$connection)
{
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($sql_data, $connection);
if (!$db_selected)
{
die ('Can\'t use db : ' . mysql_error());
}
$device_id=$_POST['uid'];
$latitude=$_POST['ulat'];
$longitude=$_POST['ulong'];
$radius4=100;
if($device_id != NULL && $latitude != NULL && $longitude != NULL){
$insert_token ="insert into geofencing_test(device_id,latitude,longitude)values ('".$device_id."','".$latitude."','".$longitude."')";
mysql_query($insert_token) or die(mysql_error()."Eroror!");
$check='{"error":"false"}';
echo $check;
$tracker = mysql_query("select latitude,longitude from gpslocations where username='".$device_id."'");
$row2 = mysql_fetch_row($tracker);
//print_r($row1 =mysql_fetch_array($access_circle));
$lat3=$row2[0];
$long3=$row2[1];
function getDistance( $latitude1, $longitude1, $latitude2, $longitude2 ) {
$earth_radius = 6371;
$dLat = deg2rad( $latitude2 - $latitude1 );
$dLon = deg2rad( $longitude2 - $longitude1 );
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * asin(sqrt($a));
$d = $earth_radius * $c;
return $d;
}
$cirradius=$radius4/1000;
$distance = getDistance($latitude,$longitude,$lat3,$long3);
if( $distance < $cirradius) {
//error_log(""+$distance,3,'D:/error.txt');
$update_sql=mysql_query("update gpslocations set extraInfo='#02f7a5' where username='".$device_id."'") or die(mysql_error());
} else {
$update_sql=mysql_query("update gpslocations set extraInfo='#f44253' where username='".$device_id."'") or die(mysql_error());
}
}else{
$check='{"error":"true"}';
echo $check;
}
?>
Style.css:-
body {
/* background-color: #ccc; */
}
.container-fluid {
border: 2px solid #4B77BE;
margin: 10px;
}
.routeSelectDark {
background-color: #ccc;
}
.col-sm-2 {
height: 50px;
}
.col-sm-3 {
height: 50px;
}
.col-sm-6 {
height: 50px;
}
.col-sm-8 {
height: 50px;
}
.col-sm-10 {
height: 50px;
}
#toplogo {
padding-top: 10px;
}
#messages {
padding-top: 19px;
text-align: right;
margin: 0px 0px 10px 0px;
}
#routeSelect {
border: 2px solid #cc4400;
width: 100%;
height:30px;
color: #000;
margin-bottom:5px;
/* background-color: #ccc; */
}
#autorefresh {
width: 100%;
margin-bottom:5px;
}
#delete {
width: 100%;
margin-bottom:5px;
}
#refresh {
width: 100%;
margin-bottom:5px;
}
#viewall {
width: 100%;
margin-bottom:5px;
}
.deletediv {
text-align: center;
}
.autorefreshdiv {
text-align: center;
}
.refreshdiv {
text-align: center;
}
.viewalldiv {
text-align: center;
}
@media only screen and (min-width : 768px) {
.container {
margin-top: 25px;
}
.deletediv {
text-align: left;
}
.autorefreshdiv {
text-align: center;
}
.refreshdiv {
text-align: center;
}
.viewalldiv {
text-align: right;
}
}
#map-canvas {
border: 4px solid #22A7F0;
width: 100%;
height: 680px;
}
#mapdiv {
height: 690px;
}
#selectdiv {
margin-bottom: 10px;
}
#halimage {
vertical-align:middle;
width: 37px;
height: 37px;
margin-bottom: 5px;
}
Hi Muthu,
ReplyDeleteCan you provide full source code and database of this geofence article at atul.rawat85@gmail.com
Regards,
Atul Rawat