1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-23 06:49:37 +02:00

Add mark_visited_region action to ReverseGeocodeViewSet and update AdventureModal for region tracking

This commit is contained in:
Sean Morley 2024-11-01 20:08:23 -04:00
parent a7a49227c4
commit b60455b50a
3 changed files with 65 additions and 35 deletions

View file

@ -1100,10 +1100,12 @@ class ReverseGeocodeViewSet(viewsets.ViewSet):
county = data['address']['county'] county = data['address']['county']
if 'city' in keys: if 'city' in keys:
city = data['address']['city'] city = data['address']['city']
print(iso_code) if not iso_code:
return {"error": "No region found"}
region = Region.objects.filter(id=iso_code).first() region = Region.objects.filter(id=iso_code).first()
visited_region = VisitedRegion.objects.filter(region=region).first() visited_region = VisitedRegion.objects.filter(region=region).first()
is_visited = False is_visited = False
print(iso_code)
country_code = iso_code[:2] country_code = iso_code[:2]
if city: if city:
@ -1123,7 +1125,6 @@ class ReverseGeocodeViewSet(viewsets.ViewSet):
def reverse_geocode(self, request): def reverse_geocode(self, request):
lat = request.query_params.get('lat', '') lat = request.query_params.get('lat', '')
lon = request.query_params.get('lon', '') lon = request.query_params.get('lon', '')
print(lat, lon)
url = f"https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat={lat}&lon={lon}" url = f"https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat={lat}&lon={lon}"
headers = {'User-Agent': 'AdventureLog Server'} headers = {'User-Agent': 'AdventureLog Server'}
response = requests.get(url, headers=headers) response = requests.get(url, headers=headers)
@ -1133,3 +1134,32 @@ class ReverseGeocodeViewSet(viewsets.ViewSet):
return Response({"error": "Invalid response from geocoding service"}, status=400) return Response({"error": "Invalid response from geocoding service"}, status=400)
return Response(self.extractIsoCode(data)) return Response(self.extractIsoCode(data))
@action(detail=False, methods=['post'])
def mark_visited_region(self, request):
# searches through all of the users adventures, if the serialized data is_visited, is true, runs reverse geocode on the adventures and if a region is found, marks it as visited. Use the extractIsoCode function to get the region
new_region_count = 0
new_regions = {}
adventures = Adventure.objects.filter(user_id=self.request.user)
serializer = AdventureSerializer(adventures, many=True)
for adventure, serialized_adventure in zip(adventures, serializer.data):
if serialized_adventure['is_visited'] == True:
lat = adventure.latitude
lon = adventure.longitude
url = f"https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat={lat}&lon={lon}"
headers = {'User-Agent': 'AdventureLog Server'}
response = requests.get(url, headers=headers)
try:
data = response.json()
except requests.exceptions.JSONDecodeError:
return Response({"error": "Invalid response from geocoding service"}, status=400)
region = self.extractIsoCode(data)
if 'error' not in region:
region = Region.objects.filter(id=region['id']).first()
visited_region = VisitedRegion.objects.filter(region=region, user_id=self.request.user).first()
if not visited_region:
visited_region = VisitedRegion(region=region, user_id=self.request.user)
visited_region.save()
new_region_count += 1
new_regions[region.id] = region.name
return Response({"new_regions": new_region_count, "regions": new_regions})

View file

@ -28,7 +28,6 @@
import ActivityComplete from './ActivityComplete.svelte'; import ActivityComplete from './ActivityComplete.svelte';
import { appVersion } from '$lib/config'; import { appVersion } from '$lib/config';
import { ADVENTURE_TYPES } from '$lib'; import { ADVENTURE_TYPES } from '$lib';
import RegionCard from './RegionCard.svelte';
let wikiError: string = ''; let wikiError: string = '';
@ -82,6 +81,12 @@
images = adventure.images || []; images = adventure.images || [];
if (longitude && latitude) {
adventure.latitude = latitude;
adventure.longitude = longitude;
reverseGeocode();
}
if (adventure.longitude && adventure.latitude) { if (adventure.longitude && adventure.latitude) {
markers = []; markers = [];
markers = [ markers = [
@ -94,12 +99,6 @@
]; ];
} }
if (longitude && latitude) {
adventure.latitude = latitude;
adventure.longitude = longitude;
reverseGeocode();
}
$: { $: {
if (!adventure.rating) { if (!adventure.rating) {
adventure.rating = NaN; adventure.rating = NaN;
@ -143,20 +142,21 @@
close(); close();
} }
let previousCoords: { lat: number; lng: number } | null = null;
$: if (markers.length > 0) { $: if (markers.length > 0) {
adventure.latitude = Math.round(markers[0].lngLat.lat * 1e6) / 1e6; const newLat = Math.round(markers[0].lngLat.lat * 1e6) / 1e6;
adventure.longitude = Math.round(markers[0].lngLat.lng * 1e6) / 1e6; const newLng = Math.round(markers[0].lngLat.lng * 1e6) / 1e6;
if (!adventure.location) {
adventure.location = markers[0].location; if (!previousCoords || previousCoords.lat !== newLat || previousCoords.lng !== newLng) {
} adventure.latitude = newLat;
if (!adventure.name) { adventure.longitude = newLng;
adventure.name = markers[0].name; previousCoords = { lat: newLat, lng: newLng };
} reverseGeocode();
} }
$: { if (!adventure.name) {
if (adventure.longitude && adventure.latitude) { adventure.name = markers[0].name;
reverseGeocode();
} }
} }

View file

@ -44,20 +44,20 @@
// URL.revokeObjectURL(url); // URL.revokeObjectURL(url);
// } // }
// async function checkVisitedRegions() { async function checkVisitedRegions() {
// let res = await fetch('/api/countries/region_check_all_adventures/', { let res = await fetch('/api/reverse-geocode/mark_visited_region/', {
// method: 'POST', method: 'POST',
// headers: { headers: {
// 'Content-Type': 'application/json' 'Content-Type': 'application/json'
// } }
// }); });
// let data = await res.json(); let data = await res.json();
// if (res.ok) { if (res.ok) {
// addToast('success', `${data.regions_visited} regions updated`); addToast('success', `${data.new_regions} regions updated`);
// } else { } else {
// addToast('error', 'Error updating visited regions'); addToast('error', 'Error updating visited regions');
// } }
// } }
</script> </script>
<h1 class="text-center font-extrabold text-4xl mb-6">{$t('settings.settings_page')}</h1> <h1 class="text-center font-extrabold text-4xl mb-6">{$t('settings.settings_page')}</h1>
@ -182,7 +182,7 @@
</form> </form>
</div> </div>
<!-- <div class="flex flex-col items-center mt-4"> <div class="flex flex-col items-center mt-4">
<h1 class="text-center font-extrabold text-xl mt-4 mb-2">Visited Region Check</h1> <h1 class="text-center font-extrabold text-xl mt-4 mb-2">Visited Region Check</h1>
<p> <p>
By selecting this, the server will check all of your visited adventures and mark the regions By selecting this, the server will check all of your visited adventures and mark the regions
@ -193,7 +193,7 @@
> >
<p>This may take longer depending on the number of adventures you have.</p> <p>This may take longer depending on the number of adventures you have.</p>
</div> </div>
<!--
<div class="flex flex-col items-center mt-4"> <div class="flex flex-col items-center mt-4">
<h1 class="text-center font-extrabold text-xl mt-4 mb-2">Data Export</h1> <h1 class="text-center font-extrabold text-xl mt-4 mb-2">Data Export</h1>
<button class="btn btn-neutral mb-4" on:click={exportAdventures}> Export to JSON </button> <button class="btn btn-neutral mb-4" on:click={exportAdventures}> Export to JSON </button>