Commit 77b8c753 by Bogdan Ungureanu

Fix View and route

parent 32e3fc8e
all:
all: build install
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,6 +5,7 @@ body {
#map-canvas {
border: 1px solid #000;
width: 100%;
/* height: 800px; */
height: 1024px;
}
......
......@@ -47,93 +47,161 @@
<script type="text/javascript">
var map;
var poly;
var bounds ;
var routes = [];
function init() {
var mapCanvas = document.getElementById('map-canvas')
var mapOptions = {
center: new google.maps.LatLng(44.4333333, 26.1),
map = new google.maps.Map(
document.getElementById('map-canvas'),
{
zoom: 7,
scaleControl: true,
rotateControl:false,
panControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(mapCanvas,mapOptions);
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
};
poly = new google.maps.Polyline(polyOptions);
bounds = new google.maps.LatLngBounds();
poly.setMap(map);
//track(1);
/*
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
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);
}
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.SATELLITE,
]
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_BOTTOM,
},
streetViewControl: false,
center: new google.maps.LatLng(44.4333333, 26.1),
}
);
*/
}
function show_track(id) {
var event = document.getElementById('event-map')
//var x = document.getElementById("mySelect").selectedIndex;
//var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
track(id,event.options[event.selectedIndex].value)
show_device_track(id,event.options[event.selectedIndex].value)
}
function track (id,events) {
function show_device_track (id,events) {
$.ajax({
url: "/track/" + id + "/" + events,
dataType: "json",
// if the data is succesfully found
success: function (data) {
var path = poly.getPath();
// Reset poly and bounds
for (var i = 0; i < path.length; i++) {
path.pop();
// Reset all tracks to default
for (i = 0,len = routes.length; i < len; ++i) {
routes[i].poly.setPath([]);
routes[i].start.setMap(null);
routes[i].end.setMap(null);
delete routes[i];
}
bounds = new google.maps.LatLngBounds();
// New map bounds
var bounds = new google.maps.LatLngBounds();
// Build routes
for (i = 0, len = data.length; i < len; ++i) {
//console.log('got' + data[i].Latitude + data[i].Longitude);
var LatLng = new google.maps.LatLng(data[i].Latitude , data[i].Longitude);
path.push(LatLng);
bounds.extend(LatLng);
/*
var path = data[i];
var loc = new google.maps.LatLng(path.Latitude , path.Longitude);
if ( typeof routes[path.Route] == "undefined" ) {
var routeColor;
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: LatLng,
title: '#' + data[i].Id + "-"+ path.getLength() + " speed "+ data[i].Speed + "km/h",
position: loc,
title: '#' + i,
map: map
});
*/
*/
}
map.fitBounds(bounds);
}
})
}
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>
<!-- /.container -->
......
......@@ -13,6 +13,11 @@ import (
"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 (
server = &GPSServer{
c: &GPSServerConfig{ // Default config
......@@ -139,6 +144,7 @@ func init() {
log.Errorf("Open log file error: %s", err)
return
}
log.SetOutput(logfd)
}
......
......@@ -7,6 +7,16 @@ import (
"time"
)
type (
TrackResponse struct {
Route int
Time string
Latitude float64
Longitude float64
Speed int
}
)
func doLogin(username, password string) (*Session, bool) {
user := &User{}
server.db.Where("name = ? and password = ?", username, password).First(&user)
......@@ -78,7 +88,6 @@ func indexPage(c *httpd.Context) {
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()
if err != nil {
log.Errorf("%s", err)
......@@ -114,19 +123,65 @@ func loginPage(c *httpd.Context) {
// Track device
func trackHandler(c *httpd.Context) {
var logs []Log
device := c.Param("device")
date, err := ParseDate(c.Param("date"))
if err != nil {
log.Printf("trackHandler error parsing time %s", err)
c.Error("Invalid date", 400)
return
}
log := &Log{Time: date}
server.db.Order("time asc").Where("did = ? AND time > ? AND time < ? ", device, log.Time, log.Time.Add(24*time.Hour)).Find(&logs)
// Load from Database
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
}
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, logs)
c.JSON(200, response)
}
// Logout
......@@ -150,17 +205,9 @@ func gpsd_router() (*httpd.Router, error) {
http.Get("/track/:device/:date", trackHandler)
http.Get("/login", loginPage)
http.Get("/logout", logoutPage)
// Assets Handlers
// Assets Handlers
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/")
return http, nil
......
......@@ -2,6 +2,7 @@ package main
import (
// log "os/logger"
"math"
"strconv"
"strings"
"time"
......@@ -98,7 +99,34 @@ func FormatTimeShort(yy, mm, dd, h, m, s string) (time.Time, error) {
int(minute),
int(second),
0,
time.UTC).Add(time.Hour)
time.UTC)
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