chore(maps): update banzone display when alarm

This commit is contained in:
Tran Anh Tuan
2025-09-29 21:11:51 +07:00
parent ef353862e4
commit b44f1a9b29
11 changed files with 386 additions and 20 deletions

View File

@@ -1,6 +1,5 @@
import { defineConfig } from '@umijs/max';
import proxy from './config/proxy';
const { REACT_APP_ENV = 'dev' } = process.env as {
REACT_APP_ENV: 'dev' | 'test' | 'prod';
};
@@ -14,6 +13,7 @@ export default defineConfig({
locale: {
default: 'vi-VN',
},
favicons: ['/logo.png'],
layout: {
title: '2025 Sản phẩm của Mobifone v1.0',
},

1
public/avatar.svg Normal file
View File

@@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1679201365371" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1897" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M509.31257004 540.79389452h4.91415801c44.99525866-0.76783723 81.39074114-16.58528313 108.26504222-46.83806846 59.12346278-66.6482671 49.29514673-180.9024399 48.2201749-191.80572705-3.83918618-81.85144307-42.53817965-121.01113989-74.48020676-139.28566479C572.42878628 149.19693275 544.63307997 141.82569571 513.61245812 141.21142578H511.00181181c-17.04598575 0-50.52368662 2.76421361-82.61928101 21.03873851-32.24916171 18.27452489-71.56242513 57.43422101-75.40161058 139.89993473-1.07497185 10.90328787-10.90328787 125.15746067 48.22017491 191.80572704 26.72073376 30.2527846 63.11621625 46.07023049 108.11147491 46.83806846z m-115.32914464-234.80461006c0-0.46070263 0.15356731-0.92140454 0.15356731-1.22853914 5.06772532-110.10785129 83.23355022-121.93254442 116.7112518-121.93254443H512.69105358c41.4632078 0.92140454 111.95066108 17.81382227 116.71125108 121.93254443 0 0.46070263 0 0.92140454 0.15356731 1.22853914 0.15356731 1.07497185 10.90328787 105.50082861-37.93115624 160.47797059-19.34949674 21.80657575-45.14882595 32.55629632-79.08722946 32.86343166h-1.53567446c-33.78483618-0.30713461-59.73773271-11.05685517-78.93366214-32.86343165-48.68087753-54.67000739-38.23829157-159.55656606-38.08472427-160.4779706z" p-id="1898"></path><path d="M827.3507296 730.29611058v-0.46070263c0-1.22853915-0.15356731-2.457079-0.15356731-3.83918618-0.92140454-30.40635263-2.91778164-101.50807511-69.56604874-124.23605539-0.46070263-0.15356731-1.07497185-0.30713461-1.53567375-0.46070264-69.25891341-17.66025497-126.84670245-57.5877883-127.46097237-58.04849021-9.3676134-6.60339979-22.26727838-4.29988808-28.87067744 5.06772532-6.60339979 9.3676134-4.29988808 22.26727838 5.0677253 28.87067743 2.6106463 1.84280907 63.73048619 44.38098873 140.20706862 64.03762079 35.78121256 12.74609694 39.77396603 50.98438852 40.84893787 85.99776458 0 1.38210717 0 2.6106463 0.15356802 3.83918545 0.15356731 13.82106951-0.76783723 35.16694264-3.22491624 47.45233838-24.87792469 14.12820412-122.39324633 62.96264895-270.73938991 62.96264823-147.73187366 0-245.86146522-48.98801213-270.89295721-63.11621625-2.457079-12.28539504-3.53205084-33.63126816-3.22491624-47.45233767 0-1.22853915 0.15356731-2.457079 0.15356802-3.83918545 1.07497185-35.01337533 5.06772532-73.25166689 40.84893786-85.99776457 76.47658314-19.65663206 137.596423-62.34837901 140.20706862-64.03762079 9.3676134-6.60339979 11.67112511-19.50306404 5.06772531-28.87067744-6.60339979-9.3676134-19.50306404-11.67112511-28.87067745-5.06772605-0.61426993 0.46070263-57.89492363 40.38823598-127.46097236 58.04849094-0.61426993 0.15356731-1.07497185 0.30713461-1.53567375 0.46070264-66.6482671 22.88154832-68.64464421 93.9832708-69.56604874 124.2360554 0 1.38210717 0 2.6106463-0.15356731 3.83918617v0.46070191c-0.15356731 7.98550697-0.30713461 48.98801213 7.83193893 69.56604875 1.53567446 3.99275348 4.29988808 7.37123702 7.98550697 9.67474873 4.60702342 3.07134893 115.02200931 73.4052342 299.76363465 73.40523419s295.15661197-70.48745329 299.76363538-73.40523419c3.53205084-2.3035117 6.44983249-5.68199525 7.98550624-9.67474873 7.67837163-20.4244693 7.52480433-61.42697448 7.37123703-69.41248072z" p-id="1899"></path></svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@@ -1,8 +1,9 @@
import { LogoutOutlined } from '@ant-design/icons';
import { history, RunTimeLayoutConfig } from '@umijs/max';
import { Dropdown } from 'antd';
import { handleRequestConfig } from '../config/Request';
import logo from '../public/logo.png';
import UnAccessPage from './components/403/403Page';
import Footer from './components/Footer/Footer';
import { ROUTE_LOGIN } from './constants';
import { parseJwt } from './utils/jwtTokenUtils';
import { getToken, removeToken } from './utils/localStorageUtils';
@@ -72,12 +73,37 @@ export const layout: RunTimeLayoutConfig = (initialState) => {
margin: 0,
paddingInline: 0,
},
avatarProps: {
size: 'small',
src: '/avatar.svg', // 👈 ở đây dùng icon thay vì src
render: (_, dom) => {
return (
<Dropdown
menu={{
items: [
{
key: 'logout',
icon: <LogoutOutlined />,
label: 'Đăng xuất',
onClick: () => {
removeToken();
history.push(ROUTE_LOGIN);
},
},
],
}}
>
{dom}
</Dropdown>
);
},
},
layout: 'mix',
logout: () => {
removeToken();
history.push(ROUTE_LOGIN);
},
footerRender: () => <Footer />,
// footerRender: () => <Footer />,
onPageChange: () => {
if (!initialState.initialState) {
history.push(ROUTE_LOGIN);

View File

@@ -1,6 +1,10 @@
export const DEFAULT_NAME = 'Umi Max';
export const TOKEN = 'token';
export const BASE_URL = 'https://sgw-device.gms.vn';
export const MAP_TRACKPOINTS_ID = 'ship-trackpoints';
export const MAP_POLYLINE_BAN = 'ban-polyline';
export const MAP_POLYGON_BAN = 'ban-polygon';
// Global Constants
// Route Constants
@@ -22,3 +26,5 @@ export const API_GET_GPS = '/api/sgw/gps';
export const API_GET_FISH = '/api/sgw/fishspecies';
export const API_UPDATE_FISHING_LOGS = '/api/sgw/fishingLog';
export const API_SOS = '/api/sgw/sos';
export const API_PATH_SHIP_TRACK_POINTS = '/api/sgw/trackpoints';
export const API_GET_ALL_BANZONES = '/api/sgw/banzones';

View File

@@ -8,7 +8,7 @@ import {
import { Feature, Map, View } from 'ol';
import { Coordinate } from 'ol/coordinate';
import { createEmpty, extend, Extent, isEmpty } from 'ol/extent';
import { MultiPolygon, Point, Polygon } from 'ol/geom';
import { LineString, MultiPolygon, Point, Polygon } from 'ol/geom';
import BaseLayer from 'ol/layer/Base';
import VectorLayer from 'ol/layer/Vector';
import { fromLonLat } from 'ol/proj';
@@ -32,10 +32,18 @@ interface StyleConfig {
textColor?: string; // màu chữ
textStrokeColor?: string; // màu viền chữ
textOffsetY?: number; // độ lệch theo trục Y
strokeColor?: string; // màu đường kẻ cho LineString
strokeWidth?: number; // độ dày đường kẻ cho LineString
fillColor?: string; // màu fill cho Polygon
borderColor?: string; // màu viền cho Polygon
borderWidth?: number; // độ dày viền cho Polygon
minScale?: number; // tỷ lệ nhỏ nhất
maxScale?: number; // tỷ lệ lớn nhất
}
// Interface for feature data
interface FeatureData {
id?: string | number;
bearing?: number;
text?: string;
}
@@ -319,7 +327,6 @@ class MapManager {
// Lưu feature
this.features.push(feature);
this.flyToFeature(feature);
this.featureLayer?.getSource()?.addFeature(feature);
console.log('Point added successfully:', { coord, data, styleConfig });
@@ -444,6 +451,90 @@ class MapManager {
}
}
// Hàm addLineString đã được sửa đổi
addLineString(
coords: Coordinate[],
data: FeatureData = {},
styleConfig: StyleConfig = {},
): Feature | null {
try {
// Kiểm tra coords là mảng hợp lệ và có ít nhất 2 tọa độ
if (
!Array.isArray(coords) ||
coords.length < 2 ||
!coords.every(
(coord) =>
Array.isArray(coord) &&
coord.length === 2 &&
typeof coord[0] === 'number' &&
typeof coord[1] === 'number',
)
) {
throw new Error(
`Invalid coordinates for LineString: ${JSON.stringify(coords)}`,
);
}
// Chuyển đổi tọa độ từ [lon, lat] sang hệ tọa độ của OpenLayers
const transformedCoords = coords.map((coord) => fromLonLat(coord));
const geometry = new LineString(transformedCoords);
const feature = new Feature({
geometry,
...data,
});
// Tạo style cho LineString
const style = new Style({
text: new Text({
text: data.text || '',
font: styleConfig.font || '16px Arial', // Tăng kích thước font
fill: new Fill({ color: styleConfig.textColor || 'black' }), // Đổi màu thành đen để nổi bật
stroke: new Stroke({
color: styleConfig.textStrokeColor || 'white',
width: 2, // Tăng độ rộng viền
}),
placement: 'line',
textAlign: 'center',
textBaseline: 'middle', // Đổi thành 'middle' để căn giữa theo chiều dọc
offsetY: styleConfig.textOffsetY || -10, // Dịch text lên trên một chút
}),
stroke: new Stroke({
color: styleConfig.strokeColor || 'blue',
width: styleConfig.strokeWidth || 5,
}),
});
feature.setStyle(style);
// Thêm feature vào features và featureLayer
if (this.featureLayer && this.isInitialized) {
this.features.push(feature);
this.featureLayer.getSource()?.addFeature(feature);
console.log(
'LineString added successfully at',
new Date().toLocaleTimeString(),
':',
{ coords, data, styleConfig },
);
// Đảm bảo bản đồ được render lại
this.map?.render();
return feature;
} else {
throw new Error('featureLayer or map is not initialized');
}
} catch (error: any) {
this.errors.push(error.message);
this.onError(this.errors);
console.error(
'Error adding LineString at',
new Date().toLocaleTimeString(),
':',
error.message,
);
return null;
}
}
createPolygonStyle = (
data: Record<string, any> = {},
styleConfig: Record<string, any> = {},
@@ -635,7 +726,7 @@ class MapManager {
view.fit(extent, {
padding: [300, 300, 300, 300],
maxZoom: features.length === 1 ? 10 : 12,
maxZoom: features.length === 1 ? 8 : 10,
duration,
});

View File

@@ -1,6 +1,21 @@
import { ROUTE_TRIP } from '@/constants';
import { queryAlarms } from '@/services/controller/DeviceController';
import {
MAP_POLYGON_BAN,
MAP_POLYLINE_BAN,
MAP_TRACKPOINTS_ID,
ROUTE_TRIP,
} from '@/constants';
import {
queryAlarms,
queryEntities,
queryShipTrackPoints,
} from '@/services/controller/DeviceController';
import { queryBanzones } from '@/services/controller/MapController';
import { getShipIcon } from '@/services/service/MapService';
import {
convertWKTLineStringToLatLngArray,
convertWKTtoLatLngString,
getBanzoneNameByType,
} from '@/utils/geomUtils';
import {
CommentOutlined,
InfoCircleOutlined,
@@ -61,34 +76,47 @@ const HomePage: React.FC = () => {
useEffect(() => {
getGPSData();
const interval = setInterval(() => {
getGPSData();
getEntitiesData();
getShipTrackPoints();
getEntityData();
}, 5000);
return () => {
mapManagerRef.current?.destroy();
clearInterval(interval);
console.log('MapManager destroyed in HomePage cleanup');
};
}, []);
useEffect(() => {
const timer = setTimeout(() => {
// getGPSData();
getEntitiesData();
}, 500); // delay 1s
getShipTrackPoints();
getEntityData();
}, 1000); // delay 1s
return () => clearTimeout(timer);
}, [gpsData]);
const getEntitiesData = async () => {
try {
const alarm = await queryAlarms();
console.log('GPS Data:', gpsData);
// console.log('Fetched alarm data:', alarm);
// console.log('GPS Data:', gpsData);
if (mapManagerRef.current?.featureLayer) {
if (mapManagerRef.current?.featureLayer && gpsData) {
// Clear trước
mapManagerRef.current.featureLayer.getSource()?.clear();
try {
mapManagerRef.current.addPoint(
[gpsData!.lon, gpsData!.lat],
// Tạo feature mới
const feature = mapManagerRef.current.addPoint(
[gpsData.lon, gpsData.lat],
{
bearing: gpsData!.h || 0,
bearing: gpsData.h || 0,
},
{
icon: getShipIcon(alarm.level || 1, gpsData?.fishing || false),
icon: getShipIcon(alarm.level || 0, gpsData?.fishing || false),
scale: 0.1,
},
);
@@ -103,6 +131,96 @@ const HomePage: React.FC = () => {
console.error('Error fetching entities:', error);
}
};
const getShipTrackPoints = async () => {
try {
const trackpoints = await queryShipTrackPoints();
// console.log('Fetched ship track points:', trackpoints.length);
if (trackpoints.length > 0) {
mapManagerRef.current?.addLineString(
trackpoints.map((point) => [point.lon, point.lat]),
{
id: MAP_TRACKPOINTS_ID,
// You can add more properties here if needed
},
{
strokeColor: 'blue',
strokeWidth: 3,
},
);
}
} catch (error) {
console.error('Error fetching ship track points:', error);
}
};
const getEntityData = async () => {
try {
const entities = await queryEntities();
console.log('Fetched entities:', entities.length);
if (entities.length > 0) {
entities.forEach(async (entity) => {
if (entity.id == '50:2') {
const banzones = await queryBanzones();
console.log('Fetched banzones:', banzones.length);
if (entity.valueString != '[]') {
const zones = JSON.parse(entity.valueString);
console.log('Parsed zones:', zones);
for (const zone of zones) {
const geom = banzones.find((b) => b.id === zone.zone_id);
if (geom) {
if (geom.geom?.geom_type === 2) {
// Polyline
const coordinates = convertWKTLineStringToLatLngArray(
geom?.geom?.geom_lines || '',
);
if (coordinates.length > 0) {
mapManagerRef.current.addLineString(
coordinates,
{
id: MAP_POLYLINE_BAN,
text: `${geom.name} - ${zone.message}`,
},
{
strokeColor: 'red',
strokeWidth: 4,
},
);
}
} else if (geom.geom?.geom_type === 1) {
const coordinates = convertWKTtoLatLngString(
geom?.geom?.geom_poly || '',
);
if (coordinates.length > 0) {
mapManagerRef.current.addPolygon(
coordinates,
{
id: MAP_POLYGON_BAN,
name: geom.name,
type: getBanzoneNameByType(geom.type || 4),
description: zone.message,
},
{
strokeColor: 'yellow',
strokeWidth: 2,
fillColor: 'rgba(255, 255, 0, 0.3)', // Màu vàng với độ trong suốt
},
);
}
}
} else {
console.log('No geometry found for zone:', zone.id);
}
}
} else {
console.log('Zone rỗng');
}
}
});
}
} catch (error) {
console.error('Error fetching entities:', error);
}
};
return (
<div>

View File

@@ -12,7 +12,6 @@ import MainTripBody from './components/MainTripBody';
import TripCancleOrFinishedButton from './components/TripCancelOrFinishButton';
const DetailTrip = () => {
const intl = useIntl();
const [responsive, setResponsive] = useState(false);
const [showAlarmList, setShowAlarmList] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [alarmList, setAlarmList] = useState<API.Alarm[]>([]);

View File

@@ -3,11 +3,12 @@ import {
API_GET_GPS,
API_PATH_ENTITIES,
API_PATH_SHIP_INFO,
API_PATH_SHIP_TRACK_POINTS,
API_SOS,
} from '@/constants';
import { request } from '@umijs/max';
function transformEntityResponse(
export function transformEntityResponse(
raw: API.EntityResponse,
): API.TransformedEntity {
return {
@@ -19,7 +20,7 @@ function transformEntityResponse(
};
}
export async function getEntities(): Promise<API.TransformedEntity[]> {
export async function queryEntities(): Promise<API.TransformedEntity[]> {
const rawList = await request<API.EntityResponse[]>(API_PATH_ENTITIES);
return rawList.map(transformEntityResponse);
}
@@ -52,3 +53,7 @@ export async function sendSosMessage(message: string) {
},
});
}
export async function queryShipTrackPoints() {
return await request<API.ShipTrackPoint[]>(API_PATH_SHIP_TRACK_POINTS);
}

View File

@@ -1,4 +1,4 @@
import { API_GET_ALL_LAYER, API_GET_LAYER_INFO } from '@/constants';
import { API_GET_ALL_BANZONES, API_GET_ALL_LAYER, API_GET_LAYER_INFO } from '@/constants';
import { request } from '@umijs/max';
export async function getLayer(name: string) {
@@ -8,3 +8,7 @@ export async function getLayer(name: string) {
export async function getAllLayer() {
return request(API_GET_ALL_LAYER);
}
export async function queryBanzones() {
return request<API.Zone[]>(API_GET_ALL_BANZONES);
}

View File

@@ -124,6 +124,14 @@ declare namespace API {
fishing: boolean;
}
interface ShipTrackPoint {
time: number;
lon: number;
lat: number;
s: number;
h: number;
}
// Trips
interface FishingGear {
name: string;
@@ -328,4 +336,36 @@ declare namespace API {
evtid?: string;
content?: string;
}
// Banzone
export interface Zone {
id?: string;
name?: string;
type?: number;
conditions?: Condition[];
enabled?: boolean;
updated_at?: Date;
geom?: Geom;
}
export interface Condition {
max?: number;
min?: number;
type?: Type;
to?: number;
from?: number;
}
export enum Type {
LengthLimit = 'length_limit',
MonthRange = 'month_range',
}
export interface Geom {
geom_type?: number;
geom_poly?: string;
geom_lines?: string;
geom_point?: string;
geom_radius?: number;
}
}

76
src/utils/geomUtils.ts Normal file
View File

@@ -0,0 +1,76 @@
export const convertWKTPointToLatLng = (wktString: string) => {
if (
!wktString ||
typeof wktString !== 'string' ||
!wktString.startsWith('POINT')
) {
return null;
}
const matched = wktString.match(/POINT\s*\(([-\d.]+)\s+([-\d.]+)\)/);
if (!matched) return null;
const lng = parseFloat(matched[1]);
const lat = parseFloat(matched[2]);
return [lng, lat]; // [longitude, latitude]
};
export const convertWKTLineStringToLatLngArray = (wktString: string) => {
if (
!wktString ||
typeof wktString !== 'string' ||
!wktString.startsWith('LINESTRING')
) {
return [];
}
const matched = wktString.match(/LINESTRING\s*\((.*)\)/);
if (!matched) return [];
const coordinates = matched[1].split(',').map((coordStr) => {
const [x, y] = coordStr.trim().split(' ').map(Number);
return [x, y]; // [lng, lat]
});
return coordinates;
};
export const convertWKTtoLatLngString = (wktString: string) => {
if (
!wktString ||
typeof wktString !== 'string' ||
!wktString.startsWith('MULTIPOLYGON')
) {
return [];
}
const matched = wktString.match(/MULTIPOLYGON\s*\(\(\((.*)\)\)\)/);
if (!matched) return [];
const polygons = matched[1]
.split(')),((') // chia các polygon
.map((polygonStr) =>
polygonStr
.trim()
.split(',')
.map((coordStr) => {
const [x, y] = coordStr.trim().split(' ').map(Number);
return [x, y];
}),
);
return polygons;
};
export const getBanzoneNameByType = (type: number) => {
switch (type) {
case 1:
return 'Cấm đánh bắt';
case 2:
return 'Cấm di chuyển';
case 3:
return 'Vùng an toàn';
default:
return 'Chưa có';
}
};