workers map
This commit is contained in:
parent
eab4596db7
commit
a49fe60889
@ -3,168 +3,157 @@
|
||||
{% load mysettings %}
|
||||
|
||||
{% block header_link %}
|
||||
<!-- Select2 -->
|
||||
<link rel="stylesheet" href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<link rel="stylesheet" href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<!-- Select2 -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
|
||||
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
|
||||
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
|
||||
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
|
||||
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
|
||||
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
|
||||
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
|
||||
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
|
||||
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
|
||||
<link rel="stylesheet" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css">
|
||||
|
||||
{% endblock header_link %}
|
||||
|
||||
{% block content %}
|
||||
<section class="content">
|
||||
<div class="container-fluid ">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-body table-responsive p-0" style="height: 85vh; padding-left: 0;">
|
||||
<table class="table table-bordered table-hover table-head-fixed text-nowrap text-sm">
|
||||
<thead>
|
||||
<section class="content">
|
||||
<div class="container-fluid ">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-body table-responsive p-0" style="height: 85vh; padding-left: 0;">
|
||||
<table class="table table-bordered table-hover table-head-fixed text-nowrap text-sm">
|
||||
<thead>
|
||||
<tr role="row">
|
||||
<th>Сотрудники ({{objects_count}})</th>
|
||||
<th>Сотрудники <span id="workersCount">( 0 )</span></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</thead>
|
||||
<tbody id="workersTableBody">
|
||||
|
||||
{% for catalog in catalog_list %}
|
||||
<tr style="padding-left:0;">
|
||||
<td>
|
||||
<form action="/ogr/edit/?id={{catalog.id}}" id="frm_name_{{catalog.id}}" method="POST" class="floatLeft butDelUser">
|
||||
{% csrf_token %}
|
||||
<a href="#" onclick="document.getElementById('frm_name_{{catalog.id}}').submit(); return false;">
|
||||
{{ catalog.name }}
|
||||
</a>
|
||||
<input type="hidden" value="{{catalog.id}}" name="id">
|
||||
</form>
|
||||
|
||||
</td>
|
||||
<td>
|
||||
<a href="#" class="text-muted">
|
||||
<i class="fas fa-bars"></i>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div> <!-- /.card-body -->
|
||||
</div> <!-- /.card -->
|
||||
</div> <!-- /.row -->
|
||||
<div class="col-md-9">
|
||||
<div class="card">
|
||||
<div class="card-body table-responsive p-0" style="height: 85vh; padding-left: 0;">
|
||||
<div id="map"></div>
|
||||
</div> <!-- /.card-body -->
|
||||
</div> <!-- /.card -->
|
||||
</div> <!-- /.row -->
|
||||
</div><!-- /.container-fluid -->
|
||||
</div>
|
||||
</section>
|
||||
</tbody>
|
||||
</table>
|
||||
</div> <!-- /.card-body -->
|
||||
</div> <!-- /.card -->
|
||||
</div> <!-- /.row -->
|
||||
<div class="col-md-9">
|
||||
<div class="card">
|
||||
<div class="card-body table-responsive p-0" style="height: 85vh; padding-left: 0;">
|
||||
<div id="map"></div>
|
||||
</div> <!-- /.card-body -->
|
||||
</div> <!-- /.card -->
|
||||
</div> <!-- /.row -->
|
||||
</div><!-- /.container-fluid -->
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block script_footer %}
|
||||
<script>
|
||||
|
||||
function createMarkers() {
|
||||
// create SVG Dom Icon
|
||||
var svg = `<svg xmlns="http://www.w3.org/2000/svg" class="svg-icon" width="10px" height="10px">
|
||||
<circle cx="5" cy="5" r="4" fill="rgb(250, 127, 0)" stroke-width="1" stroke="black" opacity="1"/>
|
||||
</svg>`,
|
||||
domIcon = new H.map.DomIcon(svg),
|
||||
markers = [],
|
||||
// array of initial positions of 40 markers
|
||||
initialPositions = [
|
||||
[53.9919212108278, 86.6710607860535],
|
||||
/*[50.98194, 12.50638],
|
||||
[51.83169, 12.19096],
|
||||
[52.19585, 14.58753],
|
||||
[51.30805, 13.55555],
|
||||
[51.36305, 11.94083],
|
||||
[51.55222, 12.05388],
|
||||
[51.29360, 13.35611],
|
||||
[53.30638, 12.75222],
|
||||
[52.58055, 13.91666],
|
||||
[52.20360, 13.15638],
|
||||
[54.03825, 12.71051],
|
||||
[50.91527, 11.71444],
|
||||
[52.91888, 12.42527],
|
||||
[52.07361, 11.62638],
|
||||
[51.36333, 14.94999],
|
||||
[53.83277, 13.66861],
|
||||
[51.88944, 14.53194],
|
||||
[51.29694, 14.12749],
|
||||
[52.38000, 13.52250],
|
||||
[51.13280, 13.76720],
|
||||
[50.97980, 10.95810],
|
||||
[50.02233, 8.57055],
|
||||
[52.13460, 7.68482],
|
||||
[53.63040, 9.98822],
|
||||
[52.47259, 13.40390],
|
||||
[50.86589, 7.14273],
|
||||
[51.22701, 6.76677],
|
||||
[48.35380, 11.7861],
|
||||
[49.49869, 11.07805],
|
||||
[51.42388, 12.23308],
|
||||
[49.21459, 7.10950],
|
||||
[48.68989, 9.22196],
|
||||
[52.35970, 13.28769],
|
||||
[52.46110, 9.68479],
|
||||
[53.04750, 8.78665],
|
||||
[49.69999, 8.64583],
|
||||
[49.94869, 7.26388],
|
||||
[49.47305, 8.51416],
|
||||
[51.03499, 8.68083]*/
|
||||
];
|
||||
|
||||
// create markers
|
||||
initialPositions.forEach(function(pos) {
|
||||
markers.push(new H.map.DomMarker({lat: pos[0], lng: pos[1]}, {
|
||||
icon: domIcon
|
||||
}));
|
||||
<script>
|
||||
var map;
|
||||
var ui;
|
||||
var markers = {}; // Хранение маркеров по `abonent_id`
|
||||
|
||||
// Функция инициализации карты
|
||||
function initializeMap() {
|
||||
var platform = new H.service.Platform({
|
||||
'apikey': '8hwYsYjgnywj3aNdHc9dLF7hLD3c2-ydDyY4tiawfNA'
|
||||
});
|
||||
|
||||
// add markers to map
|
||||
map.addObjects(markers);
|
||||
|
||||
// randomly update all markers positions in intervals
|
||||
setTimeout(updateMarkerPositions, 500);
|
||||
setInterval(updateMarkerPositions, 5000);
|
||||
|
||||
/**
|
||||
* update all markers' positions with animation using the ease function
|
||||
*/
|
||||
function updateMarkerPositions() {
|
||||
markers.forEach(function(marker) {
|
||||
// get random position 0 - 450km from map's center in random direction
|
||||
let randomPoint = map.getCenter().walk(Math.random() * 3, Math.random() * 4);
|
||||
|
||||
// update marker's position within ease function callback
|
||||
|
||||
var defaultLayers = platform.createDefaultLayers();
|
||||
map = new H.Map(
|
||||
document.getElementById('map'),
|
||||
defaultLayers.vector.normal.map,
|
||||
{
|
||||
zoom: 14,
|
||||
center: {lat: 55.351147, lng: 86.083717} // Начальные координаты
|
||||
}
|
||||
);
|
||||
|
||||
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
|
||||
ui = H.ui.UI.createDefault(map, defaultLayers);
|
||||
}
|
||||
|
||||
// Функция создания маркера для сотрудника
|
||||
function addOrUpdateMarker(abonent_id, latitude, longitude, velocity, update_time) {
|
||||
var lat = parseFloat(latitude);
|
||||
var lng = parseFloat(longitude);
|
||||
|
||||
if (isNaN(lat) || isNaN(lng)) {
|
||||
console.error('Некорректные координаты для сотрудника:', abonent_id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Если маркер для этого сотрудника уже существует, обновляем его данные и позицию
|
||||
if (markers[abonent_id]) {
|
||||
// Обновляем данные маркера
|
||||
var marker = markers[abonent_id];
|
||||
marker.setData({
|
||||
abonent_id: abonent_id,
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
velocity: velocity,
|
||||
update_time: update_time
|
||||
});
|
||||
|
||||
// Обновляем координаты с анимацией
|
||||
ease(
|
||||
marker.getGeometry(),
|
||||
randomPoint,
|
||||
4000,
|
||||
function(coord) {
|
||||
marker.setGeometry(coord);
|
||||
}
|
||||
)
|
||||
})
|
||||
marker.getGeometry(),
|
||||
{lat: lat, lng: lng},
|
||||
4000,
|
||||
function (coord) {
|
||||
marker.setGeometry(coord);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
// Создаем новый маркер
|
||||
var svg = `<svg xmlns="http://www.w3.org/2000/svg" class="svg-icon" width="10px" height="10px">
|
||||
<circle cx="5" cy="5" r="4" fill="rgb(250, 127, 0)" stroke-width="1" stroke="black" opacity="1"/>
|
||||
</svg>`;
|
||||
var icon = new H.map.DomIcon(svg);
|
||||
var marker = new H.map.DomMarker({lat: lat, lng: lng}, {icon: icon});
|
||||
|
||||
// Сохраняем данные сотрудника в маркер
|
||||
marker.setData({
|
||||
abonent_id: abonent_id,
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
velocity: velocity,
|
||||
update_time: update_time
|
||||
});
|
||||
|
||||
map.addObject(marker);
|
||||
markers[abonent_id] = marker; // Сохраняем маркер для будущих обновлений
|
||||
|
||||
// Добавляем событие клика для отображения данных сотрудника
|
||||
marker.addEventListener('tap', function (evt) {
|
||||
var data = evt.target.getData();
|
||||
var content = `
|
||||
<div>
|
||||
<strong>Абонент:</strong> ${data.abonent_id}<br>
|
||||
<strong>Координаты:</strong><br> ${data.latitude}, ${data.longitude}<br>
|
||||
<strong>Скорость:</strong> ${data.velocity} км/ч<br>
|
||||
<strong>Время обновления:</strong> ${data.update_time}
|
||||
</div>
|
||||
`;
|
||||
var bubble = new H.ui.InfoBubble(evt.target.getGeometry(), {
|
||||
content: content
|
||||
});
|
||||
ui.addBubble(bubble);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function ease(
|
||||
startCoord = {lat: 0, lng: 0},
|
||||
endCoord = {lat: 1, lng: 1},
|
||||
durationMs = 200,
|
||||
onStep = console.log,
|
||||
onComplete = function() {},
|
||||
) {
|
||||
var raf = window.requestAnimationFrame || function(f) {window.setTimeout(f, 16)},
|
||||
// Функция плавного перемещения маркера
|
||||
function ease(startCoord, endCoord, durationMs, onStep, onComplete = function () {
|
||||
}) {
|
||||
var raf = window.requestAnimationFrame || function (f) {
|
||||
window.setTimeout(f, 16)
|
||||
},
|
||||
stepCount = durationMs / 16,
|
||||
valueIncrementLat = (endCoord.lat - startCoord.lat) / stepCount,
|
||||
valueIncrementLng = (endCoord.lng - startCoord.lng) / stepCount,
|
||||
@ -172,68 +161,67 @@
|
||||
currentValueLat = startCoord.lat,
|
||||
currentValueLng = startCoord.lng,
|
||||
currentSinValue = 0;
|
||||
|
||||
|
||||
function step() {
|
||||
currentSinValue += sinValueIncrement;
|
||||
currentValueLat += valueIncrementLat * (Math.sin(currentSinValue) ** 2) * 2;
|
||||
currentValueLng += valueIncrementLng * (Math.sin(currentSinValue) ** 2) * 2;
|
||||
|
||||
if (currentSinValue < Math.PI) {
|
||||
onStep({lat: currentValueLat, lng: currentValueLng});
|
||||
raf(step);
|
||||
} else {
|
||||
onStep(endCoord);
|
||||
onComplete();
|
||||
}
|
||||
currentSinValue += sinValueIncrement;
|
||||
currentValueLat += valueIncrementLat * (Math.sin(currentSinValue) ** 2) * 2;
|
||||
currentValueLng += valueIncrementLng * (Math.sin(currentSinValue) ** 2) * 2;
|
||||
|
||||
if (currentSinValue < Math.PI) {
|
||||
onStep({lat: currentValueLat, lng: currentValueLng});
|
||||
raf(step);
|
||||
} else {
|
||||
onStep(endCoord);
|
||||
onComplete();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
raf(step);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the map to display over Berlin
|
||||
*
|
||||
* @param {H.Map} map A HERE Map instance within the application
|
||||
*/
|
||||
function moveMapTolocation(map) {
|
||||
map.setCenter({ lat: {{lat}}, lng: {{lon}} });
|
||||
map.setZoom(14);
|
||||
}
|
||||
|
||||
/**
|
||||
* Boilerplate map initialization code starts below:
|
||||
*/
|
||||
function createWorkersTableRow(worker) {
|
||||
const tr = document.createElement('tr')
|
||||
|
||||
//Step 1: initialize communication with the platform
|
||||
// In your own code, replace variable window.apikey with your own apikey
|
||||
var platform = new H.service.Platform({
|
||||
apikey: '8hwYsYjgnywj3aNdHc9dLF7hLD3c2-ydDyY4tiawfNA'
|
||||
});
|
||||
var defaultLayers = platform.createDefaultLayers();
|
||||
const tdWorkerID = document.createElement('td')
|
||||
tdWorkerID.textContent = worker.abonent_id
|
||||
|
||||
//Step 2: initialize a map - this map is centered over Europe
|
||||
var map = new H.Map(document.getElementById('map'),
|
||||
defaultLayers.vector.normal.map, {
|
||||
center: {
|
||||
lat: {{lat}}, lng: {{lon}} },
|
||||
zoom: 4,
|
||||
pixelRatio: window.devicePixelRatio || 1
|
||||
});
|
||||
// add a resize listener to make sure that the map occupies the whole container
|
||||
window.addEventListener('resize', () => map.getViewPort().resize());
|
||||
const tdWorkerCoord = document.createElement('td')
|
||||
tdWorkerCoord.textContent = `${worker.latitude}, ${worker.longitude}`
|
||||
|
||||
//Step 3: make the map interactive
|
||||
// MapEvents enables the event system
|
||||
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
|
||||
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
|
||||
tr.appendChild(tdWorkerID)
|
||||
tr.appendChild(tdWorkerCoord)
|
||||
return tr
|
||||
}
|
||||
|
||||
// Функция получения данных сотрудников с сервера и обновления их маркеров
|
||||
async function updateWorkers() {
|
||||
try {
|
||||
const response = await fetch('update_object/');
|
||||
const workers = await response.json();
|
||||
const workersTableBody = document.querySelector('#workersTableBody')
|
||||
const workersCount = document.querySelector('#workersCount')
|
||||
|
||||
workersCount.textContent = `( ${workers.length} )`
|
||||
workersTableBody.innerHTML = ''
|
||||
workers.forEach(worker => {
|
||||
addOrUpdateMarker(worker.abonent_id, worker.latitude, worker.longitude, worker.velocity, worker.update_time);
|
||||
let tableRow = createWorkersTableRow(worker)
|
||||
workersTableBody.appendChild(tableRow)
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении данных сотрудников:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Инициализация карты и периодическое обновление данных
|
||||
function init() {
|
||||
initializeMap();
|
||||
setInterval(updateWorkers, 5000); // Обновляем данные сотрудников каждые 5 секунд
|
||||
}
|
||||
|
||||
init();
|
||||
</script>
|
||||
|
||||
// Create the default UI components
|
||||
var ui = H.ui.UI.createDefault(map, defaultLayers);
|
||||
|
||||
// Now use the map as required...
|
||||
window.onload = function () {
|
||||
moveMapTolocation(map);
|
||||
}
|
||||
createMarkers();
|
||||
</script>
|
||||
{% endblock script_footer %}
|
||||
|
||||
@ -1,15 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from django.conf.urls import url
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.conf.urls import include # Используйте include() чтобы добавлять URL из каталога приложения
|
||||
|
||||
from apps.workerslocation.views.views_radiusapi import update_object
|
||||
from apps.workerslocation.views import views_main
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^$', views_main.main_index, name='main_index'),
|
||||
#url(r'^object/$', views_main.object_edit, name='object_edit'),
|
||||
#url(r'^object/block/$', views_main.object_block, name='object_block'),
|
||||
#url(r'^object/sensor/$', views_main.sensor_edit, name='sensor_edit'),
|
||||
#url(r'^object/sensor/sensor_ajax/$', views_main.sensor_ajax, name='sensor_ajax'),
|
||||
url(r'^update_object/$', update_object, name='update_object')
|
||||
]
|
||||
|
||||
|
||||
@ -218,7 +218,6 @@ def map_index(request):
|
||||
@login_required(login_url='/')
|
||||
@never_cache
|
||||
def main_index(request):
|
||||
WorkersLocation.objects.all()
|
||||
try:
|
||||
radiusapi = settingsmodule.get_settings('radiusapi','False')
|
||||
|
||||
|
||||
@ -1,52 +1,50 @@
|
||||
import traceback
|
||||
import os
|
||||
import io
|
||||
import json
|
||||
import requests
|
||||
import zoneinfo
|
||||
|
||||
from django.db.models import Q
|
||||
from django.conf import settings
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.shortcuts import redirect
|
||||
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.views.decorators.cache import never_cache
|
||||
|
||||
|
||||
from apps.workerslocation.models.workers_locations import WorkersLocation
|
||||
from sabron.util import logging
|
||||
from apps.util import generalmodule
|
||||
|
||||
from apps.general.views import settingsmodule
|
||||
|
||||
|
||||
@login_required(login_url='/')
|
||||
@never_cache
|
||||
def map_index(request):
|
||||
try:
|
||||
|
||||
mylon = str(float(settingsmodule.get_settings('longitude','86.10111978605353'))) # долгота центра
|
||||
mylat = str(float(settingsmodule.get_settings('latitude','55.344251210827814'))) # широта
|
||||
lon = str(float(settingsmodule.get_settings('longitude', '86.10111978605353'))) # долгота центра
|
||||
lat = str(float(settingsmodule.get_settings('latitude', '55.344251210827814'))) # широта
|
||||
|
||||
gtoadress = settingsmodule.get_settings('gtoadress','')
|
||||
gtouid = settingsmodule.get_settings('gtouid','')
|
||||
response = requests.get(f'{gtoadress}main?func=state&uid={gtouid}&sensors&out=json')
|
||||
json_data = json.loads(response.text)
|
||||
catalog_list=[]
|
||||
if json_data['result']=='OK':
|
||||
for data in json_data['objects']:
|
||||
#print(data)
|
||||
objects=dict()
|
||||
objects.update(id=data['id'])
|
||||
objects.update(name=data['name'])
|
||||
objects.update(lat=data['lat'])
|
||||
objects.update(lon=data['lon'])
|
||||
catalog_list.append(objects)
|
||||
context = generalmodule.get_context_template()
|
||||
context.update({
|
||||
'catalog_list':catalog_list,
|
||||
'objects_count':len(catalog_list),
|
||||
'lon':mylon.replace(',','.'),
|
||||
'lat':mylat.replace(',','.'),
|
||||
})
|
||||
return render(request,'wklocation_map.html', context)
|
||||
return render(request, 'wklocation_map.html',
|
||||
{
|
||||
'lon': lon.replace(',', '.'),
|
||||
'lat': lat.replace(',', '.'),
|
||||
})
|
||||
except Exception as err:
|
||||
logging.error(traceback.format_exc())
|
||||
logging.error(traceback.format_exc())
|
||||
|
||||
|
||||
@never_cache
|
||||
def update_object(request):
|
||||
try:
|
||||
workers = WorkersLocation.objects.filter(active=True)
|
||||
workers_mas = []
|
||||
for worker in workers:
|
||||
workers_mas.append({
|
||||
'abonent_id': worker.abonent_id,
|
||||
'latitude': worker.latitude,
|
||||
'longitude': worker.longitude,
|
||||
'velocity': worker.velocity,
|
||||
'radius': worker.radius,
|
||||
'update_time': worker.update_time.astimezone(zoneinfo.ZoneInfo(settings.TIME_ZONE)).strftime('%m.%d.%Y, %H:%M:%S'),
|
||||
})
|
||||
return JsonResponse(workers_mas, safe=False)
|
||||
except Exception as err:
|
||||
logging.error(traceback.format_exc())
|
||||
return JsonResponse([], status=500, safe=False)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user