@syncfusion/ej2-maps
Version:
The Maps component is used to visualize the geographical data and represent the statistical data of a particular geographical area on earth with user interactivity, and provides various customizing options
1,226 lines (1,185 loc) • 180 kB
text/typescript
/* eslint-disable max-len */
/**
* Helper functions for maps control
*/
import { createElement, isNullOrUndefined, remove, compile as templateComplier, merge, SanitizeHtmlHelper } from '@syncfusion/ej2-base';
import { AnimationOptions, Animation, animationMode } from '@syncfusion/ej2-base';
import { SvgRenderer } from '@syncfusion/ej2-svg-base';
import { Maps, FontModel, BorderModel, LayerSettings, ProjectionType, ISelectionEventArgs, itemSelection } from '../../index';
import { animationComplete, IAnimationCompleteEventArgs, Alignment, LayerSettingsModel, ZoomToolbarTooltipSettingsModel } from '../index';
import {
MarkerType, IShapeSelectedEventArgs, ITouches, IShapes, SelectionSettingsModel,
MarkerClusterSettingsModel, IMarkerRenderingEventArgs, MarkerSettings, markerClusterRendering,
IMarkerClusterRenderingEventArgs, MarkerClusterData
} from '../index';
import { CenterPositionModel, ConnectorLineSettingsModel, MarkerSettingsModel } from '../model/base-model';
import { ExportType } from '../utils/enum';
/**
* Specifies the size information of an element.
*/
export class Size {
/**
* Specifies the height of an element.
*/
public height: number;
/**
* Specifies the width of an element.
*/
public width: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
}
/**
* To find number from string.
*
* @param {string} value Specifies the value
* @param {number} containerSize Specifies the container size
* @returns {number} Returns the number
* @private
*/
export function stringToNumber(value: string, containerSize: number): number {
if (typeof value !== 'string') {
return value;
}
if (!isNullOrUndefined(value)) {
return value.indexOf('%') !== -1 ? (containerSize / 100) * parseInt(value, 10) : parseInt(value, 10);
}
return null;
}
/**
* Method to calculate the width and height of the maps.
*
* @param {Maps} maps Specifies the maps instance
* @returns {void}
* @private
*/
export function calculateSize(maps: Maps): Size {
maps.element.style.height = !isNullOrUndefined(maps.height) ? maps.height : 'auto';
maps.element.style.width = !isNullOrUndefined(maps.width) ? maps.width : 'auto';
maps.element.style.setProperty('display', 'block');
const containerWidth: number = maps.element.clientWidth;
const containerHeight: number = maps.element.clientHeight;
const containerElementWidth: number = (typeof maps.element.style.width === 'string') ?
stringToNumber(maps.element.style.width, containerWidth) : maps.element.style.width;
const containerElementHeight: number = (typeof maps.element.style.height === 'string') ?
stringToNumber(maps.element.style.height, containerHeight) : maps.element.style.height;
let availableSize: Size = new Size(0, 0);
if (maps.width === '0px' || maps.width === '0%' || maps.height === '0%' || maps.height === '0px') {
availableSize = new Size(0, 0);
} else {
availableSize = new Size(
stringToNumber(maps.width, containerWidth) || containerWidth || containerElementWidth || 600,
stringToNumber(maps.height, containerHeight) || containerHeight || containerElementHeight || (maps.isDevice ?
Math.min(window.innerWidth, window.innerHeight) : 450)
);
}
return availableSize;
}
/**
* Method to create svg for maps.
*
* @param {Maps} maps Specifies the map instance
* @returns {void}
* @private
*/
export function createSvg(maps: Maps): void {
maps.renderer = new SvgRenderer(maps.element.id);
maps.availableSize = calculateSize(maps);
maps.svgObject = maps.renderer.createSvg({
id: maps.element.id + '_svg',
width: maps.availableSize.width,
height: maps.availableSize.height
});
if (maps.width === '0px' || maps.width === '0%' || maps.height === '0%' || maps.height === '0px') {
maps.svgObject.setAttribute('height', '0');
maps.svgObject.setAttribute('width', '0');
}
}
/**
* Method to get the mouse position.
*
* @param {number} pageX - Specifies the pageX.
* @param {number} pageY - Specifies the pageY.
* @param {Element} element - Specifies the element.
* @returns {MapLocation} - Returns the location.
* @private
*/
export function getMousePosition(pageX: number, pageY: number, element: Element): MapLocation {
const elementRect: ClientRect = element.getBoundingClientRect();
const pageXOffset: number = element.ownerDocument.defaultView.pageXOffset;
const pageYOffset: number = element.ownerDocument.defaultView.pageYOffset;
const clientTop: number = element.ownerDocument.documentElement.clientTop;
const clientLeft: number = element.ownerDocument.documentElement.clientLeft;
const positionX: number = elementRect.left + pageXOffset - clientLeft;
const positionY: number = elementRect.top + pageYOffset - clientTop;
return new MapLocation((pageX - positionX), (pageY - positionY));
}
/**
* Method to convert degrees to radians.
*
* @param {number} deg Specifies the degree value
* @returns {number} Returns the number
* @private
*/
export function degreesToRadians(deg: number): number {
return deg * (Math.PI / 180);
}
/**
* Convert radians to degrees method.
*
* @param {number} radian Specifies the radian value
* @returns {number} Returns the number
* @private
*/
export function radiansToDegrees(radian: number): number {
return radian * (180 / Math.PI);
}
/**
* Method for converting from latitude and longitude values to points.
*
* @param {number} latitude - Specifies the latitude.
* @param {number} longitude - Specifies the longitude.
* @param {number} factor - Specifies the factor.
* @param {LayerSettings} layer - Specifies the layer settings.
* @param {Maps} mapModel - Specifies the maps.
* @returns {Point} - Returns the point values.
* @private
*/
export function convertGeoToPoint(latitude: number, longitude: number, factor: number, layer: LayerSettings, mapModel: Maps): Point {
const mapSize: Size = new Size(mapModel.mapAreaRect.width, mapModel.mapAreaRect.height);
let x: number; let y: number; let value: Point;
let lat: number; let lng: number; let temp: number;
const longitudeMinMax: MinMax = mapModel.baseMapBounds.longitude;
const latitudeMinMax: MinMax = mapModel.baseMapBounds.latitude;
let latRadian: number = degreesToRadians(latitude);
const lngRadian: number = degreesToRadians(longitude);
const type: ProjectionType = !isNullOrUndefined(mapModel.projectionType) ? mapModel.projectionType : 'Mercator';
const size: number = (mapModel.isTileMap) ? Math.pow(2, 1) * 256 : (isNullOrUndefined(factor)) ?
Math.min(mapSize.width, mapSize.height) : (Math.min(mapSize.width, mapSize.height) * factor);
if (layer.geometryType === 'Normal') {
x = isNullOrUndefined(factor) ? longitude : Math.abs((longitude - longitudeMinMax.min) * factor);
y = isNullOrUndefined(factor) ? latitude : Math.abs((latitudeMinMax.max - latitude) * factor);
} else if (layer.geometryType === 'Geographic') {
switch (type) {
case 'Mercator': {
const pixelOrigin: Point = new Point(size / 2, size / 2);
x = pixelOrigin.x + longitude * (size / 360);
const sinY: number = calculateBound(Math.sin(degreesToRadians(latitude)), -0.9999, 0.9999);
y = pixelOrigin.y + 0.5 * (Math.log((1 + sinY) / (1 - sinY))) * (-(size / (2 * Math.PI)));
break;
}
case 'Winkel3':
value = aitoff(lngRadian, latRadian);
lng = (value.x + lngRadian / (Math.PI / 2)) / 2;
lat = (value.y + latRadian) / 2;
break;
case 'Miller':
lng = lngRadian;
lat = (1.25 * Math.log(Math.tan((Math.PI / 4) + (.4 * latRadian))));
break;
case 'Eckert3':
temp = Math.sqrt(Math.PI * (4 + Math.PI));
lng = 2 / temp * lngRadian * (1 + Math.sqrt(1 - 4 * latRadian * latRadian / (Math.PI * Math.PI)));
lat = 4 / temp * latRadian;
break;
case 'AitOff':
value = aitoff(lngRadian, latRadian);
lng = value.x;
lat = value.y;
break;
case 'Eckert5':
lng = lngRadian * (1 + Math.cos(latRadian)) / Math.sqrt(2 + Math.PI);
lat = 2 * latRadian / Math.sqrt(2 + Math.PI);
break;
case 'Equirectangular':
lng = lngRadian;
lat = latRadian;
break;
case 'Eckert6': {
const epsilon: number = 1e-6;
temp = (1 + (Math.PI / 2)) * Math.sin(latRadian);
let delta: number = Infinity;
for (let i: number = 0; i < 10 && Math.abs(delta) > epsilon; i++) {
delta = (latRadian + (Math.sin(latRadian)) - temp) / (1 + Math.cos(latRadian));
latRadian = latRadian - delta;
}
temp = Math.sqrt(2 + Math.PI);
lng = lngRadian * (1 + Math.cos(latRadian)) / temp;
lat = 2 * latRadian / temp;
break;
}
}
x = (type === 'Mercator') ? x : roundTo(xToCoordinate(mapModel, radiansToDegrees(lng)), 3);
y = (type === 'Mercator') ? y : (-(roundTo(yToCoordinate(mapModel, radiansToDegrees(lat)), 3)));
}
return new Point(x, y);
}
/**
* @param {Maps} maps - Specifies the map control.
* @param {number} factor - Specifies the factor.
* @param {LayerSettings} currentLayer - Specifies the current layer.
* @param {Coordinate} markerData - Specifies the marker data.
* @returns {string} - Returns the path.
* @private
*/
export function calculatePolygonPath(maps: Maps, factor: number, currentLayer: LayerSettings, markerData: Coordinate[]): string {
let path: string = '';
if (!isNullOrUndefined(markerData) && markerData.length > 1) {
Array.prototype.forEach.call(markerData, (data: Coordinate, dataIndex: number) => {
const lat: number = data.latitude;
const lng: number = data.longitude;
const location: Point = (maps.isTileMap) ? convertTileLatLongToPoint(
new MapLocation(lng, lat), factor, maps.tileTranslatePoint, true
) : convertGeoToPoint(lat, lng, factor, currentLayer, maps);
if (dataIndex === 0) {
path += 'M ' + location.x + ' ' + location.y;
} else {
path += ' L ' + location.x + ' ' + location.y;
}
});
path += ' z ';
}
return path;
}
/**
* Converting tile latitude and longitude to point.
*
* @param {MapLocation} center Specifies the map center location
* @param {number} zoomLevel Specifies the zoom level
* @param {MapLocation} tileTranslatePoint Specifies the tile translate point
* @param {boolean} isMapCoordinates Specifies the boolean value
* @returns {MapLocation} Returns the location value
* @private
*/
export function convertTileLatLongToPoint(
center: MapLocation, zoomLevel: number, tileTranslatePoint: MapLocation, isMapCoordinates: boolean): MapLocation {
const size: number = Math.pow(2, zoomLevel) * 256;
const x: number = (center.x + 180) / 360;
const sinLatitude: number = Math.sin(center.y * Math.PI / 180);
const y: number = 0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI);
let pixelX: number = center.x;
let pixelY: number = center.y;
if (isMapCoordinates) {
pixelX = (x * size + 0.5) + tileTranslatePoint.x;
pixelY = (y * size + 0.5) + tileTranslatePoint.y;
}
return { x: pixelX, y: pixelY };
}
/**
* Method for calculate x point.
*
* @param {Maps} mapObject - Specifies the maps.
* @param {number} val - Specifies the value.
* @returns {number} - Returns the number.
* @private
*/
export function xToCoordinate(mapObject: Maps, val: number): number {
const longitudeMinMax: MinMax = mapObject.baseMapBounds.longitude;
const totalSize: number = isNullOrUndefined(mapObject.baseSize) ? mapObject.mapAreaRect.width : mapObject.mapAreaRect.width +
(Math.abs(mapObject.baseSize.width - mapObject.mapAreaRect.width) / 2);
return Math.round(totalSize * (val - longitudeMinMax.min) / (longitudeMinMax.max - longitudeMinMax.min) * 100) / 100;
}
/**
* Method for calculate y point.
*
* @param {Maps} mapObject - Specifies the maps.
* @param {number} val - Specifies the value.
* @returns {number} - Returns the number.
* @private
*/
export function yToCoordinate(mapObject: Maps, val: number): number {
const latitudeMinMax: MinMax = mapObject.baseMapBounds.latitude;
return Math.round(mapObject.mapAreaRect.height * (val - latitudeMinMax.min) / (latitudeMinMax.max - latitudeMinMax.min) * 100) / 100;
}
/**
* Method for calculate aitoff projection.
*
* @param {number} x - Specifies the x value.
* @param {number} y - Specifies the y value.
* @returns {Point} - Returns the point value.
* @private
*/
export function aitoff(x: number, y: number): Point {
const cosy: number = Math.cos(y);
const sincia: number = sinci(acos(cosy * Math.cos(x /= 2)));
return new Point(2 * cosy * Math.sin(x) * sincia, Math.sin(y) * sincia);
}
/**
* Method to round the number.
*
* @param {number} a - Specifies the a value
* @param {number} b - Specifies the b value
* @returns {number} - Returns the number
* @private
*/
export function roundTo(a: number, b: number): number {
const c: number = Math.pow(10, b);
return (Math.round(a * c) / c);
}
/**
*
* @param {number} x - Specifies the x value
* @returns {number} - Returns the number
* @private
*/
export function sinci(x: number): number {
return x / Math.sin(x);
}
/**
*
* @param {number} a - Specifies the a value
* @returns {number} - Returns the number
* @private
*/
export function acos(a: number): number {
return Math.acos(a);
}
/**
* Method to calculate bound.
*
* @param {number} value Specifies the value
* @param {number} min Specifies the minimum value
* @param {number} max Specifies the maximum value
* @returns {number} Returns the value
* @private
*/
export function calculateBound(value: number, min: number, max: number): number {
if (!isNullOrUndefined(min)) {
value = Math.max(value, min);
}
if (!(isNullOrUndefined(max))) {
value = Math.min(value, max);
}
return value;
}
/**
* To trigger the download element.
*
* @param {string} fileName Specifies the file name
* @param {ExportType} type Specifies the type
* @param {string} url Specifies the url
* @param {boolean} isDownload Specifies whether download a file.
* @returns {void}
* @private
*/
export function triggerDownload(fileName: string, type: ExportType, url: string, isDownload: boolean): void {
createElement('a', {
attrs: {
'download': fileName + '.' + (type as string).toLocaleLowerCase(),
'href': url
}
}).dispatchEvent(new MouseEvent(isDownload ? 'click' : 'move', {
view: window,
bubbles: false,
cancelable: true
}));
}
/**
* Specifies the information of the position of the point in maps.
*/
export class Point {
/**
* Defines the x position in pixels.
*/
public x: number;
/**
* Defines the y position in pixels.
*/
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
/**
* Specifies the position of the legend on the map, with options to set the
* position values as percentages. The legend is placed relative to the Maps,
* ensuring responsiveness.
*/
export class RelativePoint {
/**
* Defines the horizontal position of the legend as a percentage.
*/
public x: string;
/**
* Defines the vertical position of the legend as a percentage.
*/
public y: string;
constructor(x: string, y: string) {
this.x = x;
this.y = y;
}
}
/**
* Defines the latitude and longitude values that define a map location.
*/
export class Coordinate {
/**
* Gets or sets the latitude of a coordinate on a map.
*/
public latitude: number;
/**
* Gets or sets the longitude of a coordinate on a map.
*/
public longitude: number;
constructor(latitude: number, longitude: number) {
this.latitude = latitude;
this.longitude = longitude;
}
}
/**
* Map internal class for min and max
*
*/
export class MinMax {
public min: number;
public max: number;
constructor(min: number, max: number) {
this.min = min;
this.max = max;
}
}
/**
* Map internal class locations
*/
export class GeoLocation {
public latitude: MinMax;
public longitude: MinMax;
constructor(latitude: MinMax, longitude: MinMax) {
this.latitude = new MinMax(latitude.min, latitude.max);
this.longitude = new MinMax(longitude.min, longitude.max);
}
}
/**
* Function to measure the height and width of the text.
*
* @param {string} text Specifies the text
* @param {FontModel} font Specifies the font
* @returns {Size} Returns the size
* @private
*/
export function measureText(text: string, font: FontModel): Size {
let measureObject: HTMLElement = document.getElementById('mapsmeasuretext');
if (measureObject === null) {
measureObject = document.createElement('text');
measureObject.id = 'mapsmeasuretext';
document.body.appendChild(measureObject);
}
measureObject.innerText = text;
measureObject.style.cssText = 'position: absolute; font-size: ' + (typeof (font.size) === 'number' ? (font.size + 'px') : font.size) +
'; font-weight: ' + font.fontWeight + '; font-style: ' + font.fontStyle + '; font-family: ' + font.fontFamily +
'; visibility: hidden; top: -100; left: 0; whiteSpace: nowrap; lineHeight: normal';
return new Size(measureObject.clientWidth, measureObject.clientHeight);
}
/**
* @param {string} text - Specifies the text.
* @param {FontModel} font - Specifies the font.
* @returns {Size} - Returns the size of text.
* @private
*/
export function measureTextElement(text: string, font: FontModel): Size {
let canvas: HTMLCanvasElement = document.createElement('canvas');
// eslint-disable-next-line @typescript-eslint/tslint/config
const context = canvas.getContext('2d');
context.font = `${font.fontStyle} ${font.fontWeight} ${typeof font.size === 'number' ? font.size + 'px' : font.size} ${font.fontFamily}`;
const metrics: TextMetrics = context.measureText(text);
const width: number = metrics.width;
const height: number = parseFloat(font.size) || 16;
canvas = null;
return new Size(width, height);
}
/**
* Internal use of text options.
*
* @private
*/
export class TextOption {
public anchor: string;
public id: string;
public transform: string = '';
public x: number;
public y: number;
public text: string | string[];
public baseLine: string = 'auto';
constructor(id?: string, x?: number, y?: number, anchor?: string, text?: string | string[], transform: string = '', baseLine?: string) {
this.id = id;
this.text = text;
this.transform = transform;
this.anchor = anchor;
this.x = x;
this.y = y;
this.baseLine = baseLine;
}
}
/**
* Internal use of path options.
*
* @private
*/
export class PathOption {
public id: string;
public fill: string;
public stroke: string;
public ['stroke-width']: number;
public ['stroke-dasharray']: string;
public ['stroke-opacity']: number;
public ['fill-opacity']: number;
public d: string;
constructor(
id: string, fill: string, width: number, color: string, fillOpacity?: number, strokeOpacity?: number,
dashArray?: string, d?: string
) {
this.id = id;
this['fill-opacity'] = fillOpacity;
this['stroke-opacity'] = strokeOpacity;
this.fill = fill;
this.stroke = color;
this['stroke-width'] = width;
this['stroke-dasharray'] = dashArray;
this.d = d;
}
}
/** @private */
export class ColorValue {
public r: number;
public g: number;
public b: number;
constructor(r?: number, g?: number, b?: number) {
this.r = r;
this.g = g;
this.b = b;
}
}
/**
* Internal use of rectangle options.
*
* @private
*/
export class RectOption extends PathOption {
public x: number;
public y: number;
public height: number;
public width: number;
public rx: number;
public ry: number;
public transform: string;
public ['stroke-dasharray']: string;
constructor(
id: string, fill: string, border: BorderModel, fillOpacity: number,
rect: Rect, rx?: number, ry?: number, transform?: string, dashArray?: string
) {
super(id, fill, border.width, border.color, fillOpacity, border.opacity);
this.y = rect.y;
this.x = rect.x;
this.height = rect.height;
this.width = rect.width;
this.rx = rx ? rx : 0;
this.ry = ry ? ry : 0;
this.transform = transform ? transform : '';
this['stroke-dasharray'] = dashArray;
this['fill-opacity'] = fillOpacity;
this['stroke-opacity'] = border.opacity;
}
}
/**
* Internal use of circle options.
*
* @private
*/
export class CircleOption extends PathOption {
public cy: number;
public cx: number;
public r: number;
public ['stroke-dasharray']: string;
constructor(id: string, fill: string, border: BorderModel, fillOpacity: number,
cx: number, cy: number, r: number, dashArray: string) {
super(id, fill, border.width, border.color, fillOpacity, border.opacity, dashArray);
this.cy = cy;
this.cx = cx;
this.r = r;
this['stroke-dasharray'] = dashArray;
this['fill-opacity'] = fillOpacity;
this['stroke-opacity'] = border.opacity;
}
}
/**
* Internal use of polygon options.
*
* @private
*/
export class PolygonOption extends PathOption {
public points: string;
constructor(id: string, points: string, fill: string, width: number, color: string, fillOpacity: number = 1,
strokeOpacity: number = 1, dashArray: string = ''
) {
super(id, fill, width, color, fillOpacity, strokeOpacity, dashArray);
this.points = points;
}
}
/**
* Internal use of polyline options.
*
* @private
*/
export class PolylineOption extends PolygonOption {
constructor(id: string, points: string, fill: string, width: number, color: string,
fillOpacity: number = 1, strokeOpacity: number = 1, dashArray: string = '') {
super(id, points, fill, width, color, fillOpacity, strokeOpacity, dashArray);
}
}
/**
* Internal use of line options.
*
* @private
*/
export class LineOption extends PathOption {
public x1: number;
public y1: number;
public x2: number;
public y2: number;
constructor(id: string, line: Line, fill: string, width: number, color: string,
fillOpacity: number = 1, strokeOpacity: number = 1, dashArray: string = ''
) {
super(id, fill, width, color, fillOpacity, strokeOpacity, dashArray);
this.x1 = line.x1;
this.y1 = line.y1;
this.x2 = line.x2;
this.y2 = line.y2;
}
}
/**
* Internal use of line.
*
* @property {number} Line - Specifies the line class
* @private
*/
export class Line {
public x1: number;
public y1: number;
public x2: number;
public y2: number;
constructor(x1: number, y1: number, x2: number, y2: number) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
}
/**
* Internal use of map location type.
*
* @private
*/
export class MapLocation {
/**
* To specify x value
*/
public x: number;
/**
* To specify y value
*/
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
/**
* Internal use of type rect.
*
* @private
*/
export class Rect {
public x: number;
public y: number;
public height: number;
public width: number;
constructor(x: number, y: number, width: number, height: number) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
/**
* Defines the pattern unit types for drawing the patterns in maps.
*
* @private
*/
export type patternUnits =
/** Specifies the user space for maps. */
'userSpaceOnUse' |
/** Specifies the bounding box for the object. */
'objectBoundingBox';
/**
* Internal use for pattern creation.
*
* @property {PatternOptions} PatternOptions - Specifies the pattern option class.
* @private
*/
export class PatternOptions {
public id: string;
public patternUnits: patternUnits;
public patternContentUnits: patternUnits;
public patternTransform: string;
public x: number;
public y: number;
public width: number;
public height: number;
public href: string;
constructor(
id: string, x: number, y: number, width: number, height: number, patternUnits: patternUnits = 'userSpaceOnUse',
patternContentUnits: patternUnits = 'userSpaceOnUse', patternTransform: string = '', href: string = '') {
this.id = id;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.patternUnits = patternUnits;
this.patternContentUnits = patternContentUnits;
this.patternTransform = patternTransform;
this.href = href;
}
}
/**
* Internal rendering of text.
*
* @param {TextOption} option Specifies the text option
* @param {FontModel} style Specifies the style
* @param {string} color Specifies the color
* @param {HTMLElement | Element} parent Specifies the parent element
* @param {boolean} isMinus Specifies the boolean value
* @returns {Element} Returns the html object
* @private
*/
export function renderTextElement(
option: TextOption, style: FontModel, color: string, parent: HTMLElement | Element, isMinus: boolean = false
): Element {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const renderOptions: any = {
'id': option.id,
'x': option.x,
'y': option.y,
'fill': color,
'font-size': style.size,
'font-style': style.fontStyle,
'font-family': style.fontFamily,
'font-weight': style.fontWeight,
'text-anchor': option.anchor,
'transform': option.transform,
'opacity': style.opacity,
'dominant-baseline': option.baseLine
};
const text: string = typeof option.text === 'string' || typeof option.text === 'number' ? option.text : isMinus ? option.text[option.text.length - 1] : option.text[0];
let tspanElement: Element;
const renderer: SvgRenderer = new SvgRenderer('');
let height: number;
const htmlObject: HTMLElement = <HTMLElement>renderer.createText(renderOptions, text);
htmlObject.style['user-select'] = 'none';
htmlObject.style['font-family'] = style.fontFamily;
htmlObject.style['font-size'] = style.size;
htmlObject.style['font-weight'] = style.fontWeight;
htmlObject.style['font-color'] = style.color;
htmlObject.style['-moz-user-select'] = 'none';
htmlObject.style['-webkit-touch-callout'] = 'none';
htmlObject.style['-webkit-user-select'] = 'none';
htmlObject.style['-khtml-user-select'] = 'none';
htmlObject.style['-ms-user-select'] = 'none';
htmlObject.style['-o-user-select'] = 'none';
if (typeof option.text !== 'string' && option.text.length > 1) {
for (let i: number = 1, len: number = option.text.length; i < len; i++) {
height = (measureText(option.text[i as number], style).height);
tspanElement = renderer.createTSpan(
{
'x': option.x, 'id': option.id,
'y': (option.y) + ((isMinus) ? -(i * height) : (i * height))
},
isMinus ? option.text[option.text.length - (i + 1)] : option.text[i as number]
);
htmlObject.appendChild(tspanElement);
}
}
parent.appendChild(htmlObject);
return htmlObject;
}
/**
* @param {HTMLCollection} element - Specifies the html collection
* @param {string} markerId - Specifies the marker id
* @param {object} data - Specifies the data
* @param {number} index - Specifies the index
* @param {Maps} mapObj - Specifies the map object
* @param {string} templateType - Specifies the template type
* @returns {HTMLElement} - Returns the html element
* @private
*/
export function convertElement(element: HTMLCollection, markerId: string, data: object, index: number, mapObj: Maps, templateType: string): HTMLElement {
const childElement: HTMLElement = createElement('div', {
id: markerId, className: mapObj.element.id + '_marker_template_element'
});
childElement.style.cssText = 'position: absolute;pointer-events: auto;';
let elementLength: number = element.length;
while (elementLength > 0) {
childElement.appendChild(element[0]);
elementLength--;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (!(mapObj as any).isReact || templateType !== 'function') {
let templateHtml: string = childElement.innerHTML;
const properties: string[] = Object.keys(data);
const regExp: RegExpConstructor = RegExp;
for (let i: number = 0; i < properties.length; i++) {
if (typeof data[properties[i as number]] === 'object') {
templateHtml = convertStringToValue(templateHtml, '', data, mapObj);
// eslint-disable-next-line @typescript-eslint/ban-types
} else if ((<String>properties[i as number]).toLowerCase() !== 'latitude' && (<string>properties[i as number]).toLowerCase() !== 'longitude') {
templateHtml = templateHtml.replace(new regExp('{{:' + <string>properties[i as number] + '}}', 'g'), data[properties[i as number].toString()]);
}
}
childElement.innerHTML = templateHtml;
}
return childElement;
}
/**
*
* @param {string} value - Specifies the value
* @param {Maps} maps - Specifies the instance of the maps
* @returns {string} - Returns the string value
* @private
*/
export function formatValue(value: string, maps: Maps): string {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let formatValue: string; let formatFunction: any;
if (maps.format && !isNaN(Number(value))) {
formatFunction = maps.intl.getNumberFormat(
{ format: maps.format, useGrouping: maps.useGroupingSeparator });
formatValue = formatFunction(Number(value));
} else {
formatValue = value;
}
return formatValue;
}
/**
*
* @param {string} stringTemplate - Specifies the template
* @param {string} format - Specifies the format
* @param {object} data - Specifies the data
* @param {Maps} maps - Specifies the instance of the maps
* @returns {string} - Returns the string value
* @private
*/
export function convertStringToValue(stringTemplate: string, format: string, data: object, maps: Maps): string {
let templateHtml: string = (stringTemplate === '') ? format : stringTemplate;
const templateValue: string[] = (stringTemplate === '') ? templateHtml.split('${') : templateHtml.split('{{:');
const regExp: RegExpConstructor = RegExp;
for (let i: number = 0; i < templateValue.length; i++) {
if ((templateValue[i as number].indexOf('}}') > -1 && templateValue[i as number].indexOf('.') > -1) ||
(templateValue[i as number].indexOf('}') > -1 && templateValue[i as number].search('.') > -1)) {
const split: string[] = (stringTemplate === '') ? templateValue[i as number].split('}') : templateValue[i as number].split('}}');
for (let j: number = 0; j < split.length; j++) {
if (split[j as number].indexOf('.') > -1) {
const templateSplitValue: string = (getValueFromObject(data, split[j as number])).toString();
templateHtml = (stringTemplate === '') ?
templateHtml.split('${' + split[j as number] + '}').join(formatValue(templateSplitValue, maps)) :
templateHtml.replace(new regExp('{{:' + split[j as number] + '}}', 'g'), templateSplitValue);
}
}
}
}
return templateHtml;
}
/**
*
* @param {Element} element - Specifies the element
* @param {string} labelId - Specifies the label id
* @param {object} data - Specifies the data
* @returns {HTMLElement} - Returns the html element
* @private
*/
export function convertElementFromLabel(element: Element, labelId: string, data: object): HTMLElement {
const labelEle: Element = isNullOrUndefined(element.childElementCount) ? element[0] : element;
let templateHtml: string = labelEle.outerHTML;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const properties: any[] = Object.keys(data);
const regExp: RegExpConstructor = RegExp;
for (let i: number = 0; i < properties.length; i++) {
// eslint-disable-next-line @typescript-eslint/ban-types
templateHtml = templateHtml.replace(new regExp('{{:' + <String>properties[i as number] + '}}', 'g'), data[properties[i as number].toString()]);
}
const templateEle: HTMLElement = createElement('div', {
id: labelId,
innerHTML: templateHtml
});
templateEle.style.position = 'absolute';
return templateEle;
}
/**
*
* @param {MarkerType} shape - Specifies the shape
* @param {string} imageUrl - Specifies the image url
* @param {Point} location - Specifies the location
* @param {string} markerID - Specifies the marker id
* @param {any} shapeCustom - Specifies the shape custom
* @param {Element} markerCollection - Specifies the marker collection
* @param {Maps} maps - Specifies the instance of the maps
* @returns {Element} - Returns the element
* @private
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function drawSymbols(shape: MarkerType, imageUrl: string, location: Point, markerID: string, shapeCustom: any,
markerCollection: Element, maps: Maps): Element {
let markerEle: Element; let x: number; let y: number;
const size: Size = <Size>shapeCustom['size'];
const borderColor: string = shapeCustom['borderColor'];
const borderWidth: number = parseFloat(shapeCustom['borderWidth']);
const borderOpacity: number = parseFloat(shapeCustom['borderOpacity']);
const fill: string = shapeCustom['fill'];
const dashArray: string = shapeCustom['dashArray'];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const border: any = { color: borderColor, width: borderWidth, opacity: borderOpacity };
const opacity: number = shapeCustom['opacity'];
let rectOptions: RectOption;
const pathOptions: PathOption = new PathOption(markerID, fill, borderWidth, borderColor, opacity, borderOpacity, dashArray, '');
size.width = typeof(size.width) === 'string' ? parseInt(size.width, 10) : size.width;
size.height = typeof(size.height) === 'string' ? parseInt(size.height, 10) : size.height;
if (shape === 'Circle') {
const radius: number = (size.width + size.height) / 4;
const circleOptions: CircleOption = new CircleOption(markerID, fill, border, opacity,
location.x, location.y, radius, dashArray);
markerEle = maps.renderer.drawCircle(circleOptions) as SVGCircleElement;
} else if (shape === 'Rectangle') {
x = location.x - (size.width / 2);
y = location.y - (size.height / 2);
rectOptions = new RectOption(
markerID, fill, border, opacity, new Rect(x, y, size.width, size.height), null, null, '', dashArray
);
markerEle = maps.renderer.drawRectangle(rectOptions) as SVGRectElement;
} else if (shape === 'Image') {
x = location.x - (size.width / 2);
y = location.y - (markerID.indexOf('cluster') > -1 ? (size.height / 2) : size.height);
merge(pathOptions, { 'href': imageUrl, 'height': size.height, 'width': size.width, x: x, y: y });
markerEle = maps.renderer.drawImage(pathOptions) as SVGImageElement;
} else {
markerEle = calculateShapes(maps, shape, pathOptions, size, location, markerCollection);
}
return markerEle;
}
/**
*
* @param {object} data - Specifies the data
* @param {string} value - Specifies the value
* @returns {any} - Returns the data
* @private
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getValueFromObject(data: object, value: string): any {
if (!isNullOrUndefined(data) && !isNullOrUndefined(value)) {
const splits: string[] = value.replace(/\[/g, '.').replace(/\]/g, '').split('.');
if (splits.length === 1) {
data = data[splits[0]];
}
else {
for (let i: number = 0; i < splits.length && !isNullOrUndefined(data); i++) {
data = data[splits[i as number]];
}
}
}
return data;
}
/**
*
* @param {IMarkerRenderingEventArgs} eventArgs - Specifies the event arguments
* @param {object} data - Specifies the data
* @returns {IMarkerRenderingEventArgs} - Returns the arguments
* @private
*/
export function markerColorChoose(eventArgs: IMarkerRenderingEventArgs, data: object): IMarkerRenderingEventArgs {
const color: string = (!isNullOrUndefined(eventArgs.colorValuePath)) ? ((eventArgs.colorValuePath.indexOf('.') > -1) ? (getValueFromObject(data, eventArgs.colorValuePath)).toString() :
data[eventArgs.colorValuePath]) : data[eventArgs.colorValuePath];
eventArgs.fill = (!isNullOrUndefined(eventArgs.colorValuePath) &&
!isNullOrUndefined(color)) ?
((eventArgs.colorValuePath.indexOf('.') > -1) ? (getValueFromObject(data, eventArgs.colorValuePath)).toString() :
data[eventArgs.colorValuePath]) : eventArgs.fill;
return eventArgs;
}
/**
*
* @param {IMarkerRenderingEventArgs} eventArgs - Specifies the event arguments
* @param {object} data - Specifies the data
* @returns {IMarkerRenderingEventArgs} - Returns the arguments
* @private
*/
export function markerShapeChoose(eventArgs: IMarkerRenderingEventArgs, data: object): IMarkerRenderingEventArgs {
if (!isNullOrUndefined(eventArgs.shapeValuePath) && !isNullOrUndefined(data[eventArgs.shapeValuePath])) {
updateShape(eventArgs, data);
if (data[eventArgs.shapeValuePath] === 'Image') {
updateImageUrl(eventArgs, data);
}
} else {
updateShape(eventArgs, data);
updateImageUrl(eventArgs, data);
}
return eventArgs;
}
/**
*
* @param {any} path - contains a dot, it implies that the desired property is nested within the object.
* @param {any} data - The data object from which the value is to be retrieved. This can be any object that contains the properties specified in the path.
* @returns {any} - Returns the value of the property specified in the path.
* @private
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getValue(path: string, data: any): any {
return (path.indexOf('.') > -1) ? getValueFromObject(data, path).toString() : data[path as string];
}
/**
*
* @param {any} eventArgs - Specifies the event arguments
* @param {any} data - Specifies the data
* @private
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function updateShape(eventArgs: any, data: any): void {
if (!isNullOrUndefined(eventArgs.shapeValuePath)) {
const shape: MarkerType = getValue(eventArgs.shapeValuePath, data);
eventArgs.shape = (!isNullOrUndefined(shape) && shape.toString() !== '') ? shape : eventArgs.shape;
}
}
/**
*
* @param {any} eventArgs - Specifies the event arguments
* @param {any} data - Specifies the data
* @private
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function updateImageUrl(eventArgs: any, data: any): void {
if (!isNullOrUndefined(eventArgs.imageUrlValuePath)) {
const imageUrl: string = getValue(eventArgs.imageUrlValuePath, data);
eventArgs.imageUrl = (!isNullOrUndefined(imageUrl)) ? imageUrl : eventArgs.imageUrl;
}
}
/**
*
* @param {LayerSettings} currentLayer - Specifies the current layer
* @param {HTMLElement | Element} markerTemplate - Specifies the marker template
* @param {Maps} maps - Specifies the instance of the maps
* @param {number} layerIndex - Specifies the layer index
* @param {number} markerIndex - Specifies the marker index
* @param {Element} markerCollection - Specifies the marker collection
* @param {Element} layerElement - Specifies the layer element
* @param {boolean} check - Specifies the boolean value
* @param {boolean} zoomCheck - Specifies the boolean value
* @param {any} translatePoint - Specifies the data
* @param {boolean} allowInnerClusterSetting - Specifies the boolean value
* @returns {boolean} -Returns boolean for cluster completion
* @private
*/
export function clusterTemplate(currentLayer: LayerSettings, markerTemplate: HTMLElement | Element, maps: Maps,
layerIndex: number, markerIndex: number, markerCollection: Element,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
layerElement: Element, check: boolean, zoomCheck: boolean, translatePoint?: any,
allowInnerClusterSetting?: boolean): boolean {
let bounds1: DOMRect;
let bounds2: DOMRect;
let colloideBounds: DOMRect[] = [];
let clusterColloideBounds: Element[] = [];
let tempX: number = 0;
let tempY: number = 0;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let data: any;
const markerSetting: MarkerSettingsModel = currentLayer.markerSettings[markerIndex as number];
let options: TextOption;
let textElement: Element;
let tempElement1: Element;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let shapeCustom: any;
let tempElement: Element;
const postionY: number = (15 / 4);
let m: number = 0;
let indexCollection: number[] = [];
const clusters: MarkerClusterSettingsModel = !allowInnerClusterSetting && currentLayer.markerClusterSettings.allowClustering ?
currentLayer.markerClusterSettings : markerSetting.clusterSettings;
const style: FontModel = clusters.labelStyle;
const clusterGroup: Element = maps.renderer.createGroup({ id: maps.element.id + '_LayerIndex_' + layerIndex + '_markerCluster' });
const eventArg: IMarkerClusterRenderingEventArgs = {
cancel: false, name: markerClusterRendering, fill: clusters.fill, height: clusters.height,
width: clusters.width, imageUrl: clusters.imageUrl, shape: clusters.shape,
data: data, maps: maps, cluster: clusters, border: clusters.border
};
const containerRect: ClientRect = maps.element.getBoundingClientRect();
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
(maps.isTileMap) ? new Object() : getTranslate(maps, currentLayer, false);
let factor: number;
if (!maps.isTileMap) {
factor = maps.mapLayerPanel.calculateFactor(currentLayer);
}
let isClusteringCompleted: boolean = false;
const currentZoomFactor: number = !maps.isTileMap ? maps.mapScaleValue : maps.tileZoomLevel;
const markerGroup: NodeListOf<Element> | NodeListOf<ChildNode> = (markerSetting.clusterSettings.allowClustering
|| (currentLayer.markerClusterSettings.allowClustering && currentLayer.markerSettings.length > 1))
? markerTemplate.querySelectorAll(`[id*='LayerIndex_${layerIndex}_MarkerIndex_${markerIndex}']:not([id*='_Group'])`)
: markerTemplate.childNodes;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
maps.trigger('markerClusterRendering', eventArg, (clusterargs: IMarkerClusterRenderingEventArgs) => {
Array.prototype.forEach.call(markerGroup, (markerElement: Element, o: number) => {
indexCollection = [];
if (markerElement['style']['visibility'] !== 'hidden') {
tempElement = markerElement as Element;
bounds1 = tempElement.getBoundingClientRect() as DOMRect;
indexCollection.push(o);
if (!isNullOrUndefined(bounds1)) {
const list: number[] = (maps.markerModule.zoomedMarkerCluster.length > 0 && maps.markerModule.zoomedMarkerCluster[layerIndex as number] && maps.markerModule.zoomedMarkerCluster[layerIndex as number][o as number] && maps.markerModule.zoomedMarkerCluster[layerIndex as number][o as number].length > 0)
|| (maps.markerModule.initialMarkerCluster.length > 0 && maps.markerModule.initialMarkerCluster[layerIndex as number] && maps.markerModule.initialMarkerCluster[layerIndex as number][o as number] && maps.markerModule.initialMarkerCluster[layerIndex as number][o as number].length > 0) ?
(maps.previousScale < currentZoomFactor ? maps.markerModule.zoomedMarkerCluster[layerIndex as number][o as number] : maps.markerModule.initialMarkerCluster[layerIndex as number][o as number]) : null;
if (!isNullOrUndefined(list) && list.length !== 0 && !markerSetting.clusterSettings.allowClustering) {
Array.prototype.forEach.call(list, (currentIndex: number) => {
if (o !== currentIndex) {
const otherMarkerElement: Element = document.getElementById(maps.element.id + '_LayerIndex_' + layerIndex + '_MarkerIndex_'
+ markerIndex + '_dataIndex_' + currentIndex);
if (otherMarkerElement && otherMarkerElement['style']['visibility'] !== 'hidden') {
markerBoundsComparer(otherMarkerElement, bounds1, colloideBounds, indexCollection, currentIndex);
}
}
});
} else {
Array.prototype.forEach.call(markerGroup, (otherMarkerElement: Element, p: number) => {
if (p >= o + 1 && otherMarkerElement['style']['visibility'] !== 'hidden') {
markerBoundsComparer(otherMarkerElement, bounds1, colloideBounds, indexCollection, p);
}
});
}
markerClusterListHandler(maps, currentZoomFactor, layerIndex, o, indexCollection);
tempX = bounds1.left + bounds1.width / 2;
tempY = bounds1.top + bounds1.height;
if (colloideBounds.length > 0) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
indexCollection = indexCollection.filter((item: any, index: any, value: any) => value.indexOf(item) === index);
tempX = tempX - containerRect['left'];
tempY = (tempY - ((maps.availableSize.height <= containerRect['height']) ?
containerRect['top'] : (containerRect['bottom'] - containerRect['top'])));
const dataIndex: number = parseInt(markerElement['id'].split('_dataIndex_')[1].split('_')[0], 10);
const markerIndex: number = parseInt(markerElement['id'].split('_MarkerIndex_')[1].split('_')[0], 10);
const markerSetting: MarkerSettingsModel = currentLayer.markerSettings[markerIndex as number];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const markerData: any = markerSetting.dataSource[dataIndex as number];
let location: Point;
const longitude: number = (!isNullOrUndefined(markerSetting.longitudeValuePath)) ?
Number(getValueFromObject(markerData, markerSetting.longitudeValuePath)) :
!isNullOrUndefined(markerData['longitude']) ? parseFloat(markerData['longitude']) :
!isNullOrUndefined(markerData['Longitude']) ? parseFloat(markerData['Longitude']) : 0;
const latitude: number = (!isNullOrUndefined(markerSetting.latitudeValuePath)) ?
Number(getValueFromObject(markerData, markerSetting.latitudeValuePath)) :
!isNullOrUndefined(markerData['latitude']) ? parseFloat(markerData['latitude']) :
!isNullOrUndefined(markerData['Latitude']) ? parseFloat(markerData['Latitude']) : 0;
if (!maps.isTileMap) {
location = convertGeoToPoint(latitude, longitude, factor, currentLayer, maps);
} else if (maps.isTileMap) {
location = convertTileLatLongToPoint(new Point(longitude, latitude), maps.tileZoomLevel,
maps.tileTranslatePoint, true);
}
markerElement['style']['visibility'] = 'hidden';
if (eventArg.cancel) {
shapeCustom = {
size: new Size(clusters.width, clusters.height),
fill: clusters.fill, borderColor: