Skip to content

Commit

Permalink
Added boostrap5 as package
Browse files Browse the repository at this point in the history
Map 100% width and height
Added script add_measures to generate random measures
python manage.py add_measures Zaragoza
I need to add more cities
  • Loading branch information
frasanz committed Oct 4, 2024
1 parent c3891c8 commit fc9aca9
Show file tree
Hide file tree
Showing 5 changed files with 145 additions and 15 deletions.
73 changes: 58 additions & 15 deletions frontend/templates/frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,28 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Deck.gl Map</title>
<title>OpenRed</title>
<!-- Include Mapbox and deck.gl CDN -->
<script src="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css" rel="stylesheet" />
<script src="https://unpkg.com/deck.gl@latest/dist.min.js"></script>
<!-- Bootstrap 5 CSS -->
{% load django_bootstrap5 %}
{% bootstrap_css %}
{% bootstrap_javascript %}



</head>
<body>
<div id="map-container" style="width: 100%; height: 500px;"></div>
<body class="vh-100 vw-100">
<div id="map-container" class="w-100 h-100 position-relative"></div>

<script>
// Mapbox access token
// Mapbox access token from Django settings (passed in through the template)
const MAPBOX_ACCESS_TOKEN = "{{mapbox_token}}";
const csrfToken = "{{ csrf_token }}";

// Initialize the deck.gl map
// Initialize the Deck.gl map
const deckgl = new deck.DeckGL({
container: 'map-container',
mapboxApiAccessToken: MAPBOX_ACCESS_TOKEN,
Expand All @@ -28,18 +36,53 @@
pitch: 45,
bearing: 0
},
controller: true,
layers: [
new deck.ScatterplotLayer({
data: [
{position: [-122.4, 37.8], size: 100}
],
controller: true
});

// Function to fetch data and update the map
function fetchAndUpdateData() {
fetch('http://127.0.0.1:8000/api/measurements/', {
headers: {
'accept': 'application/json',
'X-CSRFToken': csrfToken
}
})
.then(response => response.json())
.then(data => {
// Map the API response to the format needed for deck.gl ScatterplotLayer
const points = data.map(measurement => ({
position: [measurement.longitude, measurement.latitude],
size: 10, // or use other fields from measurement for size
color: [255, 0, 0] // Use a constant color or map based on data
}));

// Create a new ScatterplotLayer with the API data
const scatterplotLayer = new deck.ScatterplotLayer({
id: 'scatterplot-layer',
data: points,
getPosition: d => d.position,
getRadius: d => d.size,
getFillColor: [255, 0, 0],
})
]
});
getFillColor: d => d.color,
radiusMinPixels: 5,
radiusMaxPixels: 10,
pickable: true
});

// Add the layer to the map
deckgl.setProps({
layers: [scatterplotLayer]
});
})
.catch(error => {
console.error('Error fetching data:', error);
});
}

// Initial fetch and update
fetchAndUpdateData();

// Set interval to fetch new data every 10 seconds (10000 milliseconds)
setInterval(fetchAndUpdateData, 10000);
</script>
</body>
</html>
Empty file added measures/management/__init__.py
Empty file.
Empty file.
86 changes: 86 additions & 0 deletions measures/management/commands/add_measures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import os
import requests
import random
import time
from django.core.management.base import BaseCommand
from django.utils import timezone

# Define constants for movement simulation
METERS_IN_LATITUDE = 1 / 111111 # Approximate conversion: 1 meter = 1 / 111111 degree latitude
METERS_IN_LONGITUDE = 1 / (111111 * 0.89) # Adjust for longitude at Zaragoza's latitude

class Command(BaseCommand):
help = 'Add measurement values via the API in a random walk'

def add_arguments(self, parser):
# Add argument for location name (optional) or latitude/longitude directly
parser.add_argument('location', type=str, nargs='?', help='Location name, e.g., Zaragoza')
parser.add_argument('--latitude', type=float, help='Starting latitude')
parser.add_argument('--longitude', type=float, help='Starting longitude')

def handle(self, *args, **options):
# URL of your API endpoint
api_url = 'http://localhost:8000/api/measurements/'

# Handle location argument or latitude/longitude directly
location = options.get('location', None)
latitude = options.get('latitude', None)
longitude = options.get('longitude', None)

# Hardcoded locations (Zaragoza example)
location_coordinates = {
'Zaragoza': (41.6488, -0.8891), # Latitude, Longitude of Zaragoza
# Add more locations if needed
}

# Determine starting coordinates based on location or provided lat/long
if location and location in location_coordinates:
current_latitude, current_longitude = location_coordinates[location]
elif latitude and longitude:
current_latitude, current_longitude = latitude, longitude
else:
self.stdout.write(self.style.ERROR('You must provide a valid location or latitude and longitude.'))
return

# Number of iterations (optional): Stop after 10 measurements
num_iterations = 1000

for _ in range(num_iterations):
# Simulate a random walk (change latitude and longitude slightly)
current_latitude += random.uniform(-1, 1) * METERS_IN_LATITUDE * 50 # Adjust for 50 meters
current_longitude += random.uniform(-1, 1) * METERS_IN_LONGITUDE * 50 # Adjust for 50 meters


# Example data to be sent
data = {
"device": 1, # Device ID
"user": 1, # User ID
"latitude": current_latitude,
"longitude": current_longitude,
"altitude": 200,
"values": {"radiation": random.uniform(50, 100)}, # Random radiation value
"dateTime": timezone.now().isoformat(), # Current time in ISO format
"accuracy": 1.0,
"unit": "Sieverts",
"notes": "Random walk measurement added via API",
"weather": {"temperature": 22, "humidity": 50}
}

# Optional: Authentication if needed (Bearer token example)
headers = {
'X-CSRFToken': 'rVFqCl8tria1mSouQnZiRlxx8URnw5ePfq1f2wFuLJEPbKwDY9O7gYEUZqVFqkH2',
'Content-Type': 'application/json',
}

# Make the POST request to the API
response = requests.post(api_url, json=data, headers=headers)

if response.status_code == 201:
self.stdout.write(self.style.SUCCESS(f'Successfully added measurement at ({current_latitude}, {current_longitude})'))
else:
self.stdout.write(self.style.ERROR(f'Failed to add measurement. Status code: {response.status_code}'))
self.stdout.write(self.style.ERROR(f'Response: {response.text}'))

# Wait for 10 seconds before adding the next measurement
time.sleep(10)

1 change: 1 addition & 0 deletions openred/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
# Other apps
'rest_framework',
'drf_yasg',
'django_bootstrap5',

# Custom apps
'devices',
Expand Down

0 comments on commit fc9aca9

Please sign in to comment.