Commit d84d3d67 authored by Thomas Frion's avatar Thomas Frion

[UPDF] Load GendUnit according map bounds

* We load the unit according the map bounds. => Better perfs
* TODO Refactor code
parent 95223bfd
......@@ -4,6 +4,7 @@ import * as L from 'leaflet';
import * as models from 'src/app/pghm-api/api/models/models';
import { ServiceService } from 'src/app/pghm-api/api/clients/service.service';
import { GendUnitService } from 'src/app/pghm-api/api/clients/gendunit.service';
import { AuthGuard } from '../services/auth-guard.service';
import { environment } from '../../environments/environment';
......@@ -36,9 +37,10 @@ export class MapComponent implements OnInit {
constructor(
private auth : AuthGuard,
private serviceApi : ServiceService,
private http : HttpClient
private auth : AuthGuard,
private serviceApi : ServiceService,
private gendApi : GendUnitService,
private http : HttpClient
)
{
this.pghmIcon = L.icon({
......@@ -71,8 +73,6 @@ export class MapComponent implements OnInit {
"<a href='mailto:" + this.unit.email + "'>" + this.unit.email + "</a><br><br>" +
MapComponent.ddToDMS(coordinates[0],coordinates[1]) + "<br>" +
"<b>Lat: </b>"+ coordinates[0] +", <b>Lon: </b>" + coordinates[1]);
// this.getGendarmeries();
}
ngOnInit(): void {
......@@ -97,8 +97,6 @@ export class MapComponent implements OnInit {
// })
// }
});
const gendLAyer = this.gendarmeries;
this.map = L.map('map', {
center: this.getCoor(this.unit.geom),
......@@ -109,19 +107,10 @@ export class MapComponent implements OnInit {
layers: [this.baseMap['OTM']]
});
this.map.on("zoomend", function(){
console.log(this.getBounds());
// if(this.getZoom() >= 12){
// if(!this.hasLayer(gendLAyer)){
// this.addLayer(gendLAyer);
// }
// }else{
// if(this.hasLayer(gendLAyer)){
// this.removeLayer(gendLAyer);
// }
// }
});
this.map.on("moveend", this.getGendarmeries.bind(this));
this.map.on("zoomend", this.getGendarmeries.bind(this));
L.control.layers(this.baseMap).addTo(this.map);
this.marker.addTo(this.map);
this.marker.openPopup();
......@@ -187,28 +176,35 @@ export class MapComponent implements OnInit {
return deg + "° " + min + "' " + sec+"''";
}
private getGendarmeries() : void {
const url = "https://static.data.gouv.fr/resources/liste-des-unites-de-gendarmerie-accueillant-du-public-comprenant-leur-geolocalisation-et-leurs-horaires-douverture/20200525-050031/export-gn2.csv";
this.gendarmeries = L.layerGroup([]);
this.http.get(url,{responseType: 'text'}).subscribe(data => {
let csvRows = data.split("\n");
for(let i = 1; i < csvRows.length - 1; i++){
const row = csvRows[i].split(';').map(this.removeQuote);
let marker = L.marker([row[13], row[12]], {icon: this.gendarmerieIcon});
marker.bindPopup(
"<b>" + row[1] + "</b><br><br>" + row[3] + "<br>" + row[2]
);
this.gendarmeries.addLayer(marker);
getGendarmeries(e) : void {
if (this.map.getZoom() <= 11) {
if(this.map.hasLayer(this.gendarmeries)){
this.map.removeLayer(this.gendarmeries);
}
},
err => {
console.log(err);
})
}
return;
}
private removeQuote(str : string ) : string {
return str.split('"').join("");
if(this.map.hasLayer(this.gendarmeries)){
this.map.removeLayer(this.gendarmeries);
}
const mapBounds = this.map.getBounds();
const bounds = {
x_min: mapBounds.getSouthWest().lng,
y_min: mapBounds.getSouthWest().lat,
x_max: mapBounds.getNorthEast().lng,
y_max: mapBounds.getNorthEast().lat,
}
this.gendarmeries = L.layerGroup([]);
this.gendApi.getInBoundaries(bounds).then(
(res) => {
res.forEach(e => {
let marker = L.marker(this.getCoor(e.geom), {icon:this.gendarmerieIcon});
marker.bindPopup("<b>"+e.name+"</b><br><br>"+e.addr+"<br>"+e.phone);
this.gendarmeries.addLayer(marker)
});
this.map.addLayer(this.gendarmeries);
},
(err) => {console.log(err);}
);
}
}
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import * as models from '../models/models';
import { ApiService } from '../api';
import { IClient } from './iclient';
import { AuthGuard } from 'src/app/services/auth-guard.service';
@Injectable({
providedIn: 'root'
})
export class GendUnitService extends ApiService<models.GendUnit> implements IClient<models.GendUnit> {
constructor(protected http: HttpClient, protected authGuard : AuthGuard) {
super(http, authGuard);
}
public all(headers?: HttpHeaders): Promise<models.GendUnit[]> {
return this.get('/services/', headers);
}
public one(selector: any, headers?: HttpHeaders): Promise<models.GendUnit> {
return this.read('/services/' + selector, headers);
}
public save(elem: models.GendUnit, headers?: HttpHeaders): Promise<models.GendUnit> {
let result : Promise<models.GendUnit>;
if(elem.id !== undefined){
result = this.update('/services/' + elem.id, JSON.stringify(elem), headers);
} else {
result = this.create('/services/', JSON.stringify(elem), headers);
}
return result;
}
public remove(elem: models.GendUnit, headers?: HttpHeaders): boolean {
return this.delete('/services/' + elem.id, headers);
}
public async getInBoundaries(boundaries: any, headers?: HttpHeaders): Promise<models.GendUnit[]>{
if(headers !== undefined)
this.defaultHeaders = headers;
else
await this.authHeader();
return this.http.post<models.GendUnit[]>(
this.baseUrl + '/units/gendarmerie/boundaries/',
JSON.stringify(boundaries),
{headers: this.defaultHeaders}
).toPromise();
}
}
......@@ -69,4 +69,14 @@ export class UnitModel {
return setting;
}
}
export interface GendUnit{
readonly id?: number,
code: string,
name: string,
geom: string,
dept: string,
addr: string,
phone: string,
}
\ No newline at end of file
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthService } from './auth.service'
import { ServiceService } from './api/clients/service.service'
import { TokenService } from './api/clients/token.service'
import { UnitService } from './api/clients/unit.service'
import { UserService } from './api/clients/user.service'
import { WebcamService } from './api/clients/webcam.service'
import { AuthService } from './auth.service';
import { GendUnitService } from './api/clients/gendunit.service';
import { ServiceService } from './api/clients/service.service'
import { TokenService } from './api/clients/token.service'
import { UnitService } from './api/clients/unit.service'
import { UserService } from './api/clients/user.service'
import { WebcamService } from './api/clients/webcam.service'
@NgModule({
declarations: [],
......@@ -15,6 +16,7 @@ import { WebcamService } from './api/clients/webcam.service'
],
providers: [
AuthService,
GendUnitService,
ServiceService,
TokenService,
UnitService,
......
......@@ -8,7 +8,9 @@ urlpatterns = [
path('units/<int:pk>', views.UnitDetail.as_view()),
path('units/<slug:code>', views.UnitDetailCode.as_view()),
path('units/settings/<slug:code>',views.SettingUnitDetail.as_view()),
path('units/gendarmerie', views.GendUnitList.as_view()),
path('units/gendarmerie/<int:pk>', views.GendUnitDetail.as_view()),
path('units/gendarmerie/<slug:code>', views.GendUnitDetailCode.as_view()),
path('units/gendarmerie/boundaries/', views.GendUnitBoundaries.as_view()),
]
\ No newline at end of file
......@@ -5,6 +5,7 @@ from rest_framework.response import Response
from django.http import Http404
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from django.contrib.gis.geos import Polygon
from unit.serializers import *
from unit.models import *
......@@ -197,7 +198,7 @@ class GendUnitDetail(APIView):
"""
=== GendUnit view: Detail by Code
"""
class GendUnitDetailCode(UnitDetail):
class GendUnitDetailCode(APIView):
def get_object(self, code):
try:
return GendUnit.objects.get(code=code)
......@@ -234,3 +235,23 @@ class GendUnitDetailCode(UnitDetail):
unit = self.get_object(code)
# We return with HTTP code 204
return Response(status = 204)
"""
=== GendUnit view: Get units inside boundaries
"""
class GendUnitBoundaries(APIView):
def post(self, request, format=None):
x_min = request.data.get('x_min')
y_min = request.data.get('y_min')
x_max = request.data.get('x_max')
y_max = request.data.get('y_max')
area = Polygon.from_bbox((x_min, y_min, x_max, y_max))
try:
units = GendUnit.objects.filter(geom__contained = area)
serializer = GendUnitSerializer(units, many = True)
return Response(serializer.data)
except GendUnit.DoesNotExist:
raise Http404
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