Commit 77b8c753 by Bogdan Ungureanu

Fix View and route

parent 32e3fc8e
all: all: build install
GOPATH=$(shell pwd) go build
\ No newline at end of file build:
@echo "Building application"
GOPATH=$(shell pwd) go build
install:
@echo "Installing binary file"
@rm -f /usr/local/bin/gpsd
cp gpsd /usr/local/bin
\ No newline at end of file
...@@ -5,7 +5,8 @@ body { ...@@ -5,7 +5,8 @@ body {
#map-canvas { #map-canvas {
border: 1px solid #000; border: 1px solid #000;
width: 100%; width: 100%;
height: 1024px; /* height: 800px; */
height: 1024px;
} }
.tmap { .tmap {
......
...@@ -47,93 +47,161 @@ ...@@ -47,93 +47,161 @@
<script type="text/javascript"> <script type="text/javascript">
var map; var map;
var poly; var routes = [];
var bounds ;
function init() { function init() {
var mapCanvas = document.getElementById('map-canvas') map = new google.maps.Map(
var mapOptions = { document.getElementById('map-canvas'),
center: new google.maps.LatLng(44.4333333, 26.1), {
zoom: 7, zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP, scaleControl: true,
}; rotateControl:false,
panControl: false,
map = new google.maps.Map(mapCanvas,mapOptions); mapTypeId: google.maps.MapTypeId.ROADMAP,
var polyOptions = { mapTypeControl: true,
strokeColor: '#000000', mapTypeControlOptions: {
strokeOpacity: 1.0, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
strokeWeight: 3 mapTypeIds: [
}; google.maps.MapTypeId.ROADMAP,
poly = new google.maps.Polyline(polyOptions); google.maps.MapTypeId.SATELLITE,
bounds = new google.maps.LatLngBounds(); ]
poly.setMap(map); },
zoomControl: true,
//track(1); zoomControlOptions: {
/* style: google.maps.ZoomControlStyle.LARGE,
var flightPlanCoordinates = [ position: google.maps.ControlPosition.RIGHT_BOTTOM,
new google.maps.LatLng(37.772323, -122.214897), },
new google.maps.LatLng(21.291982, -157.821856), streetViewControl: false,
new google.maps.LatLng(-18.142599, 178.431), center: new google.maps.LatLng(44.4333333, 26.1),
new google.maps.LatLng(-27.46758, 153.027892) }
]; );
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
*/
} }
function show_track(id) { function show_track(id) {
var event = document.getElementById('event-map') var event = document.getElementById('event-map')
//var x = document.getElementById("mySelect").selectedIndex; show_device_track(id,event.options[event.selectedIndex].value)
//var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
track(id,event.options[event.selectedIndex].value)
} }
function track (id,events) {
function show_device_track (id,events) {
$.ajax({ $.ajax({
url: "/track/" + id + "/" + events, url: "/track/" + id + "/" + events,
dataType: "json", dataType: "json",
// if the data is succesfully found
success: function (data) { success: function (data) {
var path = poly.getPath(); // Reset all tracks to default
// Reset poly and bounds for (i = 0,len = routes.length; i < len; ++i) {
for (var i = 0; i < path.length; i++) { routes[i].poly.setPath([]);
path.pop(); routes[i].start.setMap(null);
} routes[i].end.setMap(null);
bounds = new google.maps.LatLngBounds(); delete routes[i];
}
for (i = 0, len = data.length; i < len; ++i) { // New map bounds
//console.log('got' + data[i].Latitude + data[i].Longitude); var bounds = new google.maps.LatLngBounds();
var LatLng = new google.maps.LatLng(data[i].Latitude , data[i].Longitude); // Build routes
path.push(LatLng); for (i = 0, len = data.length; i < len; ++i) {
bounds.extend(LatLng); var path = data[i];
/* var loc = new google.maps.LatLng(path.Latitude , path.Longitude);
var marker = new google.maps.Marker({
position: LatLng, if ( typeof routes[path.Route] == "undefined" ) {
title: '#' + data[i].Id + "-"+ path.getLength() + " speed "+ data[i].Speed + "km/h", var routeColor;
map: map if(path.Route & 1) {
routeColor = "#710C04"
} else {
routeColor = "#B80F0A"
}
routes[path.Route] = {
poly : new google.maps.Polyline(
{
strokeColor:routeColor,
strokeOpacity: 1,
strokeWeight: 3,
}
),
start: new google.maps.Marker({
position: loc,
title: path.Time + " speed "+ path.Speed + "km/h",
icon: "http://www.google.com/mapfiles/dd-start.png",
map: map,
}),
end: new google.maps.Marker({
position: loc,
title: path.Time + " speed "+ path.Speed + "km/h",
icon: "http://www.google.com/mapfiles/dd-end.png",
map: map,
}),
};
// Set last Route position on route change
if ( path.Route > 0 ) {
var lr = routes[path.Route-1]
//lr.end.setPosition(loc)
}
// Setup route path
routes[path.Route].poly.setMap(map);
}
var route = routes[path.Route];
// Add new Path into route
route.poly.getPath().push(loc);
route.end.setPosition(loc);
route.end.setTitle(path.Time + " speed "+ path.Speed + "km/h");
bounds.extend(loc);
/* Debuf
var marker = new google.maps.Marker({
position: loc,
title: '#' + i,
map: map
}); });
*/ */
}
map.fitBounds(bounds);
}
map.fitBounds(bounds);
} }
}) })
} }
google.maps.event.addDomListener(window, 'load', init); google.maps.event.addDomListener(window, 'load', init);
/*
track = new google.maps.Polyline(
{
strokeColor: '#FF9601',
strokeOpacity: 1,
strokeWeight: 3,
});
track.setMap(map);
track.setPath([]);
var path = track.getPath();
// Reset poly and bounds
//for (var i = 0; i < path.length; i++) {
// path.pop();
//}
var bounds = new google.maps.LatLngBounds();
for (i = 0, len = data.length; i < len; ++i) {
var LatLng = new google.maps.LatLng(data[i].Latitude , data[i].Longitude);
path.push(LatLng);
bounds.extend(LatLng);
var marker = new google.maps.Marker({
position: LatLng,
title: '#' + data[i].Time + " speed "+ data[i].Speed + "km/h",
map: map
});
}
map.fitBounds(bounds);
*/
</script> </script>
<!-- /.container --> <!-- /.container -->
......
...@@ -13,6 +13,11 @@ import ( ...@@ -13,6 +13,11 @@ import (
"time" "time"
) )
/*
SELECT * FROM `logs` WHERE `time` > '2015-08-01 00:00:00' AND `time` < '2015-08-02 00:00:00' AND speed > 1
SELECT * FROM `logs` WHERE `time` > '2015-08-01 00:00:00' AND `time` < '2015-08-02 00:00:00' AND speed >= 0
*/
var ( var (
server = &GPSServer{ server = &GPSServer{
c: &GPSServerConfig{ // Default config c: &GPSServerConfig{ // Default config
...@@ -139,6 +144,7 @@ func init() { ...@@ -139,6 +144,7 @@ func init() {
log.Errorf("Open log file error: %s", err) log.Errorf("Open log file error: %s", err)
return return
} }
log.SetOutput(logfd) log.SetOutput(logfd)
} }
......
...@@ -7,6 +7,16 @@ import ( ...@@ -7,6 +7,16 @@ import (
"time" "time"
) )
type (
TrackResponse struct {
Route int
Time string
Latitude float64
Longitude float64
Speed int
}
)
func doLogin(username, password string) (*Session, bool) { func doLogin(username, password string) (*Session, bool) {
user := &User{} user := &User{}
server.db.Where("name = ? and password = ?", username, password).First(&user) server.db.Where("name = ? and password = ?", username, password).First(&user)
...@@ -78,7 +88,6 @@ func indexPage(c *httpd.Context) { ...@@ -78,7 +88,6 @@ func indexPage(c *httpd.Context) {
ProxyTotal int64 ProxyTotal int64
}{} }{}
//SELECT DATE_FORMAT(`time`, '%Y-%m-%d') FROM `logs` WHERE 1 GROUP BY DATE_FORMAT(`time`,'%Y%m%d')
rows, err := server.db.Raw("SELECT DATE_FORMAT(`time`, '%Y-%m-%d') FROM `logs` WHERE 1 GROUP BY DATE_FORMAT( `time` , '%Y%m%d' ) ").Rows() rows, err := server.db.Raw("SELECT DATE_FORMAT(`time`, '%Y-%m-%d') FROM `logs` WHERE 1 GROUP BY DATE_FORMAT( `time` , '%Y%m%d' ) ").Rows()
if err != nil { if err != nil {
log.Errorf("%s", err) log.Errorf("%s", err)
...@@ -114,19 +123,65 @@ func loginPage(c *httpd.Context) { ...@@ -114,19 +123,65 @@ func loginPage(c *httpd.Context) {
// Track device // Track device
func trackHandler(c *httpd.Context) { func trackHandler(c *httpd.Context) {
var logs []Log
device := c.Param("device") device := c.Param("device")
date, err := ParseDate(c.Param("date")) date, err := ParseDate(c.Param("date"))
if err != nil { if err != nil {
log.Printf("trackHandler error parsing time %s", err) log.Printf("trackHandler error parsing time %s", err)
c.Error("Invalid date", 400) c.Error("Invalid date", 400)
return return
} }
log := &Log{Time: date} // Load from Database
server.db.Order("time asc").Where("did = ? AND time > ? AND time < ? ", device, log.Time, log.Time.Add(24*time.Hour)).Find(&logs) var logs []Log
server.db.Order("time asc").Where(
"did = ? AND time > ? AND time < ?",
device,
date,
date.Add(24*time.Hour),
).Find(&logs)
var response []TrackResponse
// Todo: Read location from device config
loc, err := time.LoadLocation("Europe/Bucharest")
if err != nil {
log.Errorf("Error loading location %s", err)
c.Error("Invalid date", 400)
return
}
c.JSON(200, logs) var route = 0
var distance = 0
var lastmove = 0
for point, waypoint := range logs {
if point > 0 {
last := logs[point-1]
distance = int(Distance(waypoint.Latitude, waypoint.Longitude, last.Latitude, waypoint.Longitude))
}
// Process waypoints
if distance > 5 {
if point-lastmove > 5 {
last := logs[lastmove]
dist := int(Distance(waypoint.Latitude, waypoint.Longitude, last.Latitude, waypoint.Longitude))
if dist > 15 {
route += 1
}
}
response = append(
response,
TrackResponse{
Route: route,
Time: waypoint.Time.In(loc).Format("3:04pm"),
Latitude: waypoint.Latitude,
Longitude: waypoint.Longitude,
Speed: waypoint.Speed,
},
)
lastmove = point
}
}
c.JSON(200, response)
} }
// Logout // Logout
...@@ -150,17 +205,9 @@ func gpsd_router() (*httpd.Router, error) { ...@@ -150,17 +205,9 @@ func gpsd_router() (*httpd.Router, error) {
http.Get("/track/:device/:date", trackHandler) http.Get("/track/:device/:date", trackHandler)
http.Get("/login", loginPage) http.Get("/login", loginPage)
http.Get("/logout", logoutPage) http.Get("/logout", logoutPage)
// Assets Handlers
// Assets Handlers
assets := http.Subrouter("/assets") assets := http.Subrouter("/assets")
/*
pwd, err := os.Getwd()
if err != nil {
//fmt.Println(err)
os.Exit(1)
}
*/
assets.ServeFiles("/*filepath", server.c.http_root+"assets/") assets.ServeFiles("/*filepath", server.c.http_root+"assets/")
return http, nil return http, nil
......
...@@ -2,6 +2,7 @@ package main ...@@ -2,6 +2,7 @@ package main
import ( import (
// log "os/logger" // log "os/logger"
"math"
"strconv" "strconv"
"strings" "strings"
"time" "time"
...@@ -98,7 +99,34 @@ func FormatTimeShort(yy, mm, dd, h, m, s string) (time.Time, error) { ...@@ -98,7 +99,34 @@ func FormatTimeShort(yy, mm, dd, h, m, s string) (time.Time, error) {
int(minute), int(minute),
int(second), int(second),
0, 0,
time.UTC).Add(time.Hour) time.UTC)
return t, nil return t, nil
} }
// haversin(θ) function
func hsin(theta float64) float64 {
return math.Pow(math.Sin(theta/2), 2)
}
// Distance function returns the distance (in meters) between two points of
// a given longitude and latitude relatively accurately (using a spherical
// approximation of the Earth) through the Haversin Distance Formula for
// great arc distance on a sphere with accuracy for small distances
//
// point coordinates are supplied in degrees and converted into rad. in the func
//
// distance returned is METERS!!!!!!
// http://en.wikipedia.org/wiki/Haversine_formula
func Distance(lat1, lon1, lat2, lon2 float64) float64 {
var la1, lo1, la2, lo2, r float64
la1 = lat1 * math.Pi / 180
lo1 = lon1 * math.Pi / 180
la2 = lat2 * math.Pi / 180
lo2 = lon2 * math.Pi / 180
r = 6378100 // Earth radius in METERS
// calculate
h := hsin(la2-la1) + math.Cos(la1)*math.Cos(la2)*hsin(lo2-lo1)
return 2 * r * math.Asin(math.Sqrt(h))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment