UNPKG

@map.ir/services-sdk

Version:

JavaScript/TypeScript SDK for map.ir services

1 lines 11.4 kB
{"version":3,"file":"mapir_services_sdk.cjs","sources":["../src/utils.ts","../src/route.ts","../src/index.ts"],"sourcesContent":["/** Determines value is not undefined or null. */\nexport const isValue = <T>(value: T | undefined | null): value is T =>\n (value as T) !== undefined && (value as T) !== null;\n\ntype NonNullableProp<T, Cond> = {\n [P in keyof T]: Exclude<T[P], Cond>;\n};\n\n/** Cleans Object from undefined, null (normal), and also falsy valus (strict) */\nexport const cleanObj = <T extends Record<string, unknown>>(\n obj: T,\n strict = true\n) =>\n Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => (strict ? Boolean(v) : isValue(v)))\n ) as NonNullableProp<T, undefined | null>;\n\n/** converts all properties of an object to string, using .toString method. */\nexport const convertAllPropsToString = (obj: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [key, String(value)])\n ) as Record<string, string>;\n\n/** Generates a Url Query from a given object */\ntype StringConvetable = unknown & { toString(): string };\nexport const qs = <T extends Record<string, StringConvetable>>(obj: T) =>\n new URLSearchParams(convertAllPropsToString(cleanObj(obj))).toString();\n\n/** Converts numbers in a string to Farsi (persian) numebrs */\nexport const toFaDigits = function (input: string | number) {\n input = input.toString();\n if (!input) return \"\";\n const id = [\"۰\", \"۱\", \"۲\", \"۳\", \"۴\", \"۵\", \"۶\", \"۷\", \"۸\", \"۹\"];\n return input.replace(/[0-9]/g, function (w) {\n return id[+w];\n });\n};\n","import { qs, convertAllPropsToString } from \"./utils\";\n\nimport type { Route, Waypoint } from \"osrm\";\nimport type { LngLat } from \"./types\";\nimport type Mapir from \"./\";\n\nexport default function route(\n this: Mapir,\n locations: LngLat[],\n type: RouteType = \"car\",\n options: IRouteOptions = {}\n) {\n const defaultOptions = {\n alternatives: true,\n steps: true,\n overview: false,\n };\n const actualType = (\n {\n car: \"route\",\n walking: \"walking\",\n bicycle: \"bicycle\",\n } as Record<RouteType, string>\n )[type];\n\n try {\n const locationsString = locations\n .map((lnglat) => [lnglat.lng, lnglat.lat].join())\n .join(\";\");\n\n const actualOptions = Object.assign(defaultOptions, options);\n\n const q = qs(convertAllPropsToString(actualOptions as IRouteOptions));\n const url = new URL(\n `/routes/${actualType}/v1/driving/${locationsString}?${q}`,\n this.baseURL\n );\n\n return fetch(url, {\n method: \"GET\" as RouteMethod,\n headers: {\n \"x-api-key\": this.apiKey,\n \"content-type\": \"application/json\",\n },\n })\n .then((res) => res.json())\n .then((res) => res as IRouteResponse | undefined);\n } catch (err) {\n console.error(\"🚀 ~ file: route.ts:34 ~ err:\", err);\n return undefined;\n }\n}\n\n//** Types: */ */\n\nexport type RouteType = \"car\" | \"walking\" | \"bicycle\";\nexport interface IRouteOptions extends Record<string, unknown> {\n alternatives?: boolean;\n steps?: boolean;\n overview?: boolean;\n}\nexport type RouteMethod = \"GET\";\nexport interface IStaticMapPayload extends Record<string, string> {\n width: `${number}`;\n height: `${number}`;\n markers: `color:${\"red\" | \"blue\"}|${number},${number}|${string}`;\n zoom_level: `${number}`;\n}\n\nexport interface IRouteResponse {\n code: \"ok\";\n routes: Route[];\n waypoints: Waypoint[];\n}\n","import { qs } from \"./utils\";\n\nimport route from \"./route\";\n\nimport type { Point } from \"geojson\";\nimport type { LngLat } from \"./types\";\n\nexport default class Mapir {\n apiKey: string = \"\";\n baseURL?: string = \"https://map.ir\";\n\n constructor(opt?: IConstructorOptions) {\n const { apiKey, baseURL } = opt ?? {};\n if (apiKey) this.apiKey = apiKey;\n if (baseURL) this.baseURL = baseURL;\n }\n\n search(text: string, location: LngLat, autocomplete?: boolean) {\n const url = new URL(\n `/search${autocomplete ? \"/autocomplete\" : \"\"}`,\n this.baseURL\n );\n\n return fetch(url, {\n method: \"POST\" as SearchMethod,\n headers: {\n \"x-api-key\": this.apiKey,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n text,\n returnid: true,\n location: {\n type: \"Point\",\n coordinates: [location.lng, location.lat],\n },\n } as ISearchPayload),\n })\n .then((res) => res.json())\n .then((res) => res as ISearchResult | undefined);\n }\n\n reverseGeocode(location: LngLat) {\n const q = qs({\n lat: location.lat.toString(),\n lon: location.lng.toString(),\n } as IReversePayload);\n const url = new URL(`/reverse?${q}`, this.baseURL);\n\n return fetch(url, {\n method: \"GET\" as ReverseMethod,\n headers: {\n \"x-api-key\": this.apiKey,\n \"content-type\": \"application/json\",\n },\n })\n .then((res) => res.json())\n .then((res) => res as IReverseResult | undefined);\n }\n\n public route = route;\n\n staticMap(\n location: [LngLat] | [LngLat, LngLat],\n options?: IStaticMapOptions\n ) {\n const {\n width = 700,\n height = 500,\n zoom = 13,\n colors = [\"red\", \"red\"],\n labels,\n } = options ?? {};\n\n const markers = location\n .map((loc, idx) => {\n return [\n `color:${colors[idx]}`,\n [loc.lng, loc.lat].join(),\n labels?.[idx],\n ]\n .filter(Boolean)\n .join(\"|\");\n })\n .join();\n\n const q = qs({\n markers,\n width: String(width),\n height: String(height),\n zoom_level: String(zoom),\n } as IStaticMapPayload);\n const url = new URL(`/static?${q}`, this.baseURL);\n\n return fetch(url, {\n method: \"GET\" as StaticMapMethod,\n headers: {\n \"x-api-key\": this.apiKey,\n },\n })\n .then((res) => res.blob())\n .then((res) => res as StaticMapResult | undefined);\n }\n}\n\nexport interface IConstructorOptions {\n apiKey?: string;\n baseURL?: string;\n}\n\n//** Search v1 */ */\n\nexport type SearchMethod = \"POST\";\nexport interface ISearchPayload {\n location: Point;\n returnid: boolean;\n text: string;\n}\nexport interface ISearchResult {\n \"odata.count\": number;\n request_id: number;\n value: Array<{\n Address: string;\n City: string;\n Coordinate: { lat: number; lon: number };\n FClass: string;\n Id: string;\n Province: string;\n Text: string;\n Title: string;\n Type: string;\n }>;\n}\n\n//** Reverse Geocode */ */\n\nexport type ReverseMethod = \"POST\";\nexport interface IReversePayload extends Record<string, string> {\n lat: `${number}`;\n lon: `${number}`;\n}\nexport interface IReverseResult {\n address: string;\n address_compact: string;\n city: string;\n country: string;\n county: string;\n district: string;\n geom: Point;\n last: string;\n name: string;\n neighbourhood: string;\n penult: string;\n plaque: string;\n poi: string;\n postal_address: string;\n postal_code: string;\n primary: string;\n province: string;\n region: string;\n rural_district: string;\n village: string;\n}\n\n//** Static Map */ */\nexport interface IStaticMapOptions {\n width?: number | `${number}`;\n height?: number | `${number}`;\n colors?: [string] | [string, string];\n labels?: [string] | [string, string];\n zoom?: number | `${number}`;\n}\nexport type StaticMapMethod = \"GET\";\nexport interface IStaticMapPayload extends Record<string, string> {\n width: `${number}`;\n height: `${number}`;\n markers: `color:${\"red\" | \"blue\"}|${number},${number}|${string}`;\n zoom_level: `${number}`;\n}\nexport type StaticMapResult = Blob;\n"],"names":["convertAllPropsToString","obj","Object","fromEntries","entries","map","_ref2","String","qs","URLSearchParams","strict","filter","_ref","v","Boolean","value","cleanObj","toString","route","locations","type","options","actualType","car","walking","bicycle","locationsString","lnglat","lng","lat","join","actualOptions","assign","alternatives","steps","overview","q","url","URL","this","baseURL","fetch","method","headers","apiKey","then","res","json","err","console","error","Mapir","opt","_proto","prototype","search","text","location","autocomplete","body","JSON","stringify","returnid","coordinates","reverseGeocode","lon","staticMap","_ref2$width","width","_ref2$height","height","_ref2$zoom","zoom","_ref2$colors","colors","labels","markers","loc","idx","zoom_level","blob"],"mappings":"AACO,IAiBMA,EAA0B,SAACC,GACtC,OAAAC,OAAOC,YACLD,OAAOE,QAAQH,GAAKI,IAAI,SAAAC,GAAkB,MAAA,CAAbA,EAAA,GAAmBC,OAAZD,EAAM,IAAoB,GACrC,EAIhBE,EAAK,SAA6CP,GAC7D,OAAA,IAAIQ,gBAAgBT,EAjBE,SACtBC,EACAS,GAEA,YAFM,IAANA,IAAAA,GAAS,GAETR,OAAOC,YACLD,OAAOE,QAAQH,GAAKU,OAAO,SAAAC,GAAE,IAAGC,EAACD,YAAOF,EAASI,QAAQD,GAZ1DE,MAYuEF,CAAE,GACjC,CAWGG,CAASf,KAAOgB,UAAU,ECpBhD,SAAAC,EAEt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