@sk-global/js-msearch-gsi-jp 2.1.19 → 2.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.module.js +1 -1
- package/dist/index.module.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=require("global-mercator"),r=require("axios"),t=require("axios-cache-interceptor"),o=require("point-in-polygon"),n=require("mapbox-vector-tile");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/a(r),s=/*#__PURE__*/a(o);function c(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,o=Array(r);t<r;t++)o[t]=e[t];return o}function u(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return c(e,r);var t={}.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?c(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)({}).hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},l.apply(null,arguments)}var f={JP:{zoomBase:10,tileUrl:"https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf",layer:"japanese-admins",getResult:function(e){var r,t;return{code:5===String(e.id).length?String(e.id):"0"+String(e.id),prefecture:null==(r=e.properties)?void 0:r.prefecture,city:null==(t=e.properties)?void 0:t.city}}}};f.DEFAULT=f.JP;var p=t.setupCache(i.default.create({timeout:2e3}),{ttl:864e5});p.interceptors.request.use(function(e){var r=
|
|
1
|
+
var e=require("global-mercator"),r=require("axios"),t=require("axios-cache-interceptor"),o=require("point-in-polygon"),n=require("mapbox-vector-tile");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/a(r),s=/*#__PURE__*/a(o);function c(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,o=Array(r);t<r;t++)o[t]=e[t];return o}function u(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return c(e,r);var t={}.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?c(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)({}).hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},l.apply(null,arguments)}var f={JP:{zoomBase:10,tileUrl:"https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf",layer:"japanese-admins",getResult:function(e){var r,t;return{code:5===String(e.id).length?String(e.id):"0"+String(e.id),prefecture:null==(r=e.properties)?void 0:r.prefecture,city:null==(t=e.properties)?void 0:t.city}}}};f.DEFAULT=f.JP;var p=t.setupCache(i.default.create({timeout:2e3}),{ttl:864e5});p.interceptors.request.use(function(e){var r,t,o=null!=(r=e.baseURL)?r:"",n=null!=(t=e.url)?t:"",a=e.params?"?"+new URLSearchParams(e.params).toString():"";return console.log("Full URL:",""+o+n+a),e});var d=f.DEFAULT,g=function(r,t){try{var o=l({},d,t),a=e.lngLatToGoogle(r,o.zoomBase),c=a[0],f=a[1];return Promise.resolve(function(e,r,t,o){void 0===o&&(o=i.default);try{var a,s=function(e){return new n.VectorTile(a)},c=t.tileUrl.replace("{z}",String(t.zoomBase)).replace("{x}",String(e)).replace("{y}",String(r)),u=function(e,r){try{var t=Promise.resolve(o.get(c,{responseType:"arraybuffer"})).then(function(e){a=Buffer.from(e.data,"binary")})}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(0,function(e){throw e});return Promise.resolve(u&&u.then?u.then(s):s())}catch(e){return Promise.reject(e)}}(c,f,o,p)).then(function(e){var t=function(e,r,t,o,n){var a=Object.keys(e.layers);Array.isArray(a)||(a=[a]);var i={};return a.forEach(function(c){var l=e.layers[c];if(l&&n.layer===l.name)for(var f=0;f<l.length;f++){var p=l.feature(f).toGeoJSON(r,t,n.zoomBase);if(a.length>1&&(p.properties.vt_layer=c),p.geometry&&"Polygon"===p.geometry.type)s.default(o,p.geometry.coordinates[0])&&(i=n.getResult(p));else if(p.geometry&&"MultiPolygon"===p.geometry.type)for(var d,g=u(p.geometry.coordinates);!(d=g()).done;)if(s.default(o,d.value[0])){i=n.getResult(p);break}}}),i}(e,c,f,r,o);return{results:{muniCd:t.code,lv01Nm:t.city},code:t.code,prefecture:t.prefecture,city:t.city}})}catch(e){return Promise.reject(e)}},v=function(e){var r=e.lat,t=e.lon;try{return Promise.resolve(p.get("https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress",{responseType:"json",params:{lat:r,lon:t}})).then(function(e){var r,t,o=e.data;return l({},o,{code:null==o||null==(r=o.results)?void 0:r.muniCd,city:null==o||null==(t=o.results)?void 0:t.lv01Nm})})}catch(e){return Promise.reject(e)}},m=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g;exports.getCityMap=function(){try{return Promise.resolve(function(e,r){try{var t=Promise.resolve(i.default.get("https://maps.gsi.go.jp/js/muni.js",{responseType:"text",timeout:500})).then(function(e){return r={},e.data.split("\n").forEach(function(e){if(m.test(e)){var t=function(e){var r=e.replace(m,"$1"),t=r.split(",");if(4!==t.length)throw new Error("invalid muni record: "+r);var o=t[0],n=t[1],a=t[2],i=t[3];return a=a.padStart(5,"0"),{prefCode:o=o.padStart(2,"0"),prefName:n,cityCode:a,cityName:i}}(e);r[t.cityCode]=t}}),r;var r})}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(0,function(e){return console.log("Failed to get muni map: "+e),{}}))}catch(e){return Promise.reject(e)}},exports.getElevation=function(e,r){try{return Promise.resolve(p.get("https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php",{responseType:"json",params:{lat:e,lon:r}})).then(function(t){var o=parseFloat(t.data.elevation);return{longitude:r,latitude:e,elevation:o}})}catch(e){return Promise.reject(e)}},exports.gsiReverseGeocoder=v,exports.latLonToAddress=function(e,r){try{return Promise.resolve(function(t,o){try{var n=Promise.resolve(g([r,e])).then(function(e){if(!e.code)throw new Error("Failed to get city code from open reverse geocoder");return e})}catch(e){return o(e)}return n&&n.then?n.then(void 0,o):n}(0,function(t){return console.log(t),console.log("Failed to get city code from open reverse geocoder. Try to get from GSI."),v({lat:e,lon:r})}))}catch(e){return Promise.reject(e)}},exports.openReverseGeocoder=g,exports.searchAddress=function(e){try{return Promise.resolve(i.default.get("https://msearch.gsi.go.jp/address-search/AddressSearch",{responseType:"json",params:{q:e}})).then(function(e){return e.data})}catch(e){return Promise.reject(e)}};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/countryOptions.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/muni.ts","../src/msearch.ts"],"sourcesContent":["import {\n ReverseGeocodingOptions,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\n\n/**\n * vector tiles settings for each country\n */\nconst countryOptions: { [s: string]: ReverseGeocodingOptions } = {\n JP: {\n zoomBase: 10,\n // tileUrl: `http://127.0.0.1:5500/docs/tiles/{z}/{x}/{y}.pbf`,\n tileUrl: 'https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf',\n layer: 'japanese-admins',\n getResult: function (feature: GeoJSON.Feature) {\n const res: ReverseGeocodingResultJP = {\n code:\n 5 === String(feature.id).length\n ? String(feature.id)\n : `0${String(feature.id)}`,\n prefecture: feature.properties?.prefecture,\n city: feature.properties?.city,\n };\n return res;\n },\n },\n};\n\n// default country options\ncountryOptions.DEFAULT = countryOptions.JP;\n\nexport default countryOptions;\n","import { lngLatToGoogle } from 'global-mercator';\nimport axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport {\n ReverseGeocodingOptions,\n ReverseGeocodingResult,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\nimport countryOptions from './countryOptions';\nimport { getTile, getTileResult } from './utils';\n\ntype LngLat = [number, number];\n\nconst api = setupCache(\n axios.create({\n timeout: 2000,\n }),\n {\n ttl: 60 * 60 * 24 * 1000, // 1 day\n }\n);\n\napi.interceptors.request.use((config) => {\n const fullUrl = `${config.baseURL}${config.url}?${new URLSearchParams(\n config.params\n ).toString()}`;\n console.log('Full URL:', fullUrl);\n return config;\n});\n\nconst defaultOptions = countryOptions.DEFAULT;\n\n/**\n * Performs reverse geocoding to obtain location information based on longitude and latitude.\n *\n * @param lnglat - The longitude and latitude coordinates.\n * @param options - Optional parameters for reverse geocoding.\n * @returns A promise that resolves to the reverse geocoding result.\n */\nconst openReverseGeocoder = async (\n lnglat: LngLat,\n options?: ReverseGeocodingOptions\n): Promise<ReverseGeocodingResultJP> => {\n const opt = { ...defaultOptions, ...options };\n const [x, y] = lngLatToGoogle(lnglat, opt.zoomBase);\n const tile = await getTile(x, y, opt, api);\n const result: any = getTileResult(tile, x, y, lnglat, opt);\n return {\n results: {\n muniCd: result.code,\n lv01Nm: result.city,\n },\n code: result.code,\n prefecture: result.prefecture,\n city: result.city,\n };\n};\n\n/**\n * Performs reverse geocoding using the GSI (Geospatial Information Authority of Japan) API.\n * Given latitude and longitude coordinates, it returns the corresponding municipality code and city name.\n *\n * @param {Object} params - The parameters for the reverse geocoding request.\n * @param {number} params.lat - The latitude coordinate.\n * @param {number} params.lon - The longitude coordinate.\n * @returns {Promise<ReverseGeocodingResultJP>} A promise that resolves to an object containing the municipality code and city name.\n *\n * @example\n * const result = await gsiReverseGeocoder({ lat: 35.6895, lon: 139.6917 });\n * console.log(result); // { code: '13101', city: 'Chiyoda-ku' }\n */\nconst gsiReverseGeocoder = async ({\n lat,\n lon,\n}: {\n lat: number;\n lon: number;\n}): Promise<ReverseGeocodingResultJP> => {\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n const results = response.data;\n return {\n ...results,\n code: results?.results?.muniCd,\n city: results?.results?.lv01Nm,\n };\n};\n\n/**\n * Retrieves the elevation for a given longitude and latitude using the GSI API.\n *\n * @param {Object} coordinates - The coordinates for which to get the elevation.\n * @param {number} coordinates.lon - The longitude of the location.\n * @param {number} coordinates.lat - The latitude of the location.\n * @returns {Promise<{ longitude: number, latitude: number, elevation: number }>}\n * A promise that resolves to an object containing the longitude, latitude, and elevation.\n */\nconst getElevation = async (\n lat: number,\n lon: number\n): Promise<{ longitude: number; latitude: number; elevation: number }> => {\n // first, get elevation from GSI\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n\n const elevation = parseFloat(response.data.elevation);\n return { longitude: lon, latitude: lat, elevation };\n};\n\n/**\n * Reverse geocodes the given longitude and latitude to obtain a city code.\n *\n * @param {Object} params - The parameters for reverse geocoding.\n * @param {number} params.lon - The longitude of the location.\n * @param {number} params.lat - The latitude of the location.\n *\n * @returns {Promise<ReverseGeocodingResult>} A promise that resolves to the reverse geocoding result.\n *\n * @throws Will attempt to use an alternative geocoding service if the primary service fails.\n */\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodingResult> => {\n // first, get city code from open reverse geocoder(local)\n try {\n const result = await openReverseGeocoder([lon, lat]);\n // nếu như không thể lấy được code từ open reverse geocoder, thì sẽ lấy từ GSI\n if (!result.code) {\n throw new Error('Failed to get city code from open reverse geocoder');\n }\n\n return result;\n } catch (error) {\n // if failed, get city code from GSI\n console.log('Failed to get city code from open reverse geocoder. Try to get from GSI.');\n return gsiReverseGeocoder({ lat, lon });\n }\n};\n\nexport {\n latLonToAddress,\n getElevation,\n gsiReverseGeocoder,\n openReverseGeocoder,\n};\n","import pointInPolygon from 'point-in-polygon';\nimport axios, { AxiosInstance } from 'axios';\nimport { VectorTile } from 'mapbox-vector-tile';\nimport { ReverseGeocodingOptions, ReverseGeocodingResult } from './interfaces/index';\n\n/**\n * Get a tile from targeted country's tilesets by using x and y tile index\n * @param x x tile index\n * @param y y tile index\n * @param options ReverseGeocodingOptions\n * @param api Axios object\n * @returns VectorTile object\n */\nexport const getTile = async (\n x: number,\n y: number,\n options: ReverseGeocodingOptions,\n api: AxiosInstance = axios\n): Promise<VectorTile> => {\n const tileUrl = options.tileUrl\n .replace('{z}', String(options.zoomBase))\n .replace('{x}', String(x))\n .replace('{y}', String(y));\n\n let buffer;\n\n try {\n const res = await api.get(tileUrl, { responseType: 'arraybuffer' });\n buffer = Buffer.from(res.data, 'binary');\n } catch (error) {\n throw error;\n }\n\n const tile = new VectorTile(buffer);\n return tile;\n};\n\n/**\n * Get a result of reverse geocoding\n * @param tile VectorTile object\n * @param x x tile index\n * @param y y tile index\n * @param lnglat number[] longitude, latitude\n * @param options ReverseGeocodingOptions\n * @returns an object of result of reverse gecoding\n */\nexport const getTileResult = (\n tile: VectorTile,\n x: number,\n y: number,\n lnglat: [number, number],\n options: ReverseGeocodingOptions\n): ReverseGeocodingResult => {\n let layers = Object.keys(tile.layers);\n\n if (!Array.isArray(layers)) layers = [layers];\n\n let geocodingResult: ReverseGeocodingResult = {};\n layers.forEach((layerID) => {\n const layer = tile.layers[layerID];\n if (layer && options.layer === layer.name) {\n for (let i = 0; i < layer.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const feature: any = layer.feature(i).toGeoJSON(x, y, options.zoomBase);\n if (layers.length > 1) feature.properties.vt_layer = layerID;\n\n // Check if point is inside polygon\n // feature.geometry.coordinates is the polygon coordinates\n if (feature.geometry && feature.geometry.type === 'Polygon') {\n const coordinates = feature.geometry.coordinates[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n }\n } else if (feature.geometry && feature.geometry.type === 'MultiPolygon') {\n // Handle MultiPolygon: check if point is in any polygon\n const polygons = feature.geometry.coordinates;\n for (const polygon of polygons) {\n const coordinates = polygon[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n break;\n }\n }\n }\n }\n }\n });\n return geocodingResult;\n};\n\n","// Muni file url\nconst MuniURL = 'https://maps.gsi.go.jp/js/muni.js';\nconst MuniRegex = /GSI\\.MUNI_ARRAY\\[\"\\d+\"\\]\\s*=\\s*'(.*?)';/g;\n\nimport axios from 'axios';\n\ninterface MuniRecord {\n prefCode: string;\n prefName: string;\n cityCode: string;\n cityName: string;\n}\n\ninterface MuniMap {\n [key: string]: MuniRecord;\n}\n\ninterface AddressResults {\n muniCd: string;\n lv01Nm: string;\n mesh_code?: string;\n notes?: string;\n}\n\n/**\n * parse muni.js\n * @param muniMap\n */\nconst parseMuniMap = (muniMap: string) => {\n const muniMapObj: MuniMap = {};\n const lines = muniMap.split('\\n');\n lines.forEach((line) => {\n if (MuniRegex.test(line)) {\n const muniRecord = parseMuniRecord(line);\n muniMapObj[muniRecord.cityCode] = muniRecord;\n }\n });\n return muniMapObj;\n};\n\n/**\n * parse muni record\n * @param line\n */\nconst parseMuniRecord = (line: string) => {\n const muniRecord = line.replace(MuniRegex, '$1');\n\n const muniRecordArray = muniRecord.split(',');\n\n // validate muni record\n if (muniRecordArray.length !== 4) {\n throw new Error(`invalid muni record: ${muniRecord}`);\n }\n\n let [prefCode, prefName, cityCode, cityName] = muniRecordArray;\n\n // if cityCode is not 5 digits, add 0 to the beginning\n cityCode = cityCode.padStart(5, '0');\n\n // if prefCode is not 2 digits, add 0 to the beginning\n prefCode = prefCode.padStart(2, '0');\n\n return {\n prefCode: prefCode,\n prefName: prefName,\n cityCode: cityCode,\n cityName: cityName,\n };\n};\n\n/**\n * Fetches the municipality map data from a specified URL.\n *\n * @returns {Promise<object>} A promise that resolves to the parsed municipality map data.\n *\n * @throws Will log an error message and return an empty object if the request fails.\n */\nconst getMuniMap = async () => {\n try {\n const response = await axios.get(MuniURL, {\n responseType: 'text',\n timeout: 500,\n });\n\n const muniMap = response.data;\n return parseMuniMap(muniMap);\n } catch (error) {\n console.log(`Failed to get muni map: ${error}`);\n return {};\n }\n};\n\n/**\n * converts muni code to address name.\n *\n * @param muniMap\n * @param muniCode\n */\nconst muniCodeToAddressName = (muniMap: MuniMap, muniCode: string) => {\n const muniRecord = muniMap[muniCode];\n if (!muniRecord) {\n throw new Error(`muni code ${muniCode} not found`);\n }\n\n const add = `${muniRecord.prefName}${muniRecord.cityName}`;\n return add.replace(/ /g, '');\n};\n\n/**\n * converts address result to address name.\n * @param muniMap\n * @param addressResults\n */\nconst addressResultsToAddressName = (\n muniMap: MuniMap,\n addressResults: AddressResults\n) => {\n const mc = addressResults.muniCd;\n const muniName = muniCodeToAddressName(muniMap, mc);\n const addrName = `${muniName}${addressResults.lv01Nm}`;\n return addrName;\n};\n\nconst getMuniMapLocations = async () => {\n const muniMap = await getMuniMap();\n // muniMap is a map of all cities and wards in Japan\n // key: city code, value: { prefCode, prefName, cityCode, cityName }\n // we need to convert this to a map of all locations in Japan\n // key: prefCode , value: { prefName, cities: { key: cityCode, value: { cityCode, cityName, wards: { key: wardCode, value: { wardCode, wardName } } } } }\n\n const muniMapLocations = {};\n Object.keys(muniMap).forEach((cityCode) => {\n const muniRecord = muniMap[cityCode];\n const { prefCode, prefName, cityName } = muniRecord;\n if (!muniMapLocations[prefCode]) {\n muniMapLocations[prefCode] = { prefName, cities: {} };\n }\n\n // if cityName contains ' ', it is a ward\n // otherwise, it is a city\n if (cityName.includes(' ')) {\n // ward name is after ' '\n const [name, wardName] = cityName.split(' ');\n // find city has the same name\n const city: any = Object.values(muniMap).find(\n (c: any) => c.cityName === name\n );\n if (!city) {\n console.log(`City ${name} not found in prefCode ${prefCode}`);\n } else {\n // add ward to city\n muniMapLocations[prefCode].cities[city.cityCode].wards[cityCode] = {\n prefCode,\n cityCode: cityCode,\n cityName: `${name}${wardName}`,\n bigCityFlag: '1',\n bigCityCode: city.cityCode,\n };\n }\n } else {\n muniMapLocations[prefCode].cities[cityCode] = {\n prefCode,\n cityCode,\n cityName,\n wards: {},\n };\n }\n });\n\n // assign bigCityFlag to each city\n Object.keys(muniMapLocations).forEach((prefCode) => {\n const pref = muniMapLocations[prefCode];\n Object.keys(pref.cities).forEach((cityCode) => {\n const city = pref.cities[cityCode];\n const isBigCity = Object.values(city.wards).length > 0;\n if (isBigCity) {\n city.bigCityFlag = '2';\n } else {\n // delete wards\n delete city.wards;\n // if city is tokyo then bigCityFlag is 3, otherwise 0\n if (city.prefCode === '13') {\n city.bigCityFlag = '3';\n } else {\n city.bigCityFlag = '0';\n }\n }\n });\n });\n\n return muniMapLocations;\n};\n\nexport { getMuniMap };\n","import axios from 'axios';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\n\ntype Geometry = {\n coordinates: number[];\n type: string;\n};\n\ntype Properties = {\n addressCode: string;\n title: string;\n dataSource: string;\n};\ninterface SearchResults {\n geometry: Geometry;\n type: string;\n properties: Properties;\n}\n\n/**\n * search address by query\n */\nconst searchAddress = async (q: string): Promise<SearchResults> => {\n const url = `${BaseURL}/address-search/AddressSearch`;\n const response = await axios.get(url, {\n responseType: 'json',\n params: {\n q,\n },\n });\n\n const res = response.data;\n return res;\n};\n\nexport { searchAddress };\n"],"names":["countryOptions","JP","zoomBase","tileUrl","layer","getResult","feature","_feature$properties","_feature$properties2","code","String","id","length","prefecture","properties","city","DEFAULT","api","setupCache","axios","create","timeout","ttl","interceptors","request","use","config","fullUrl","baseURL","url","URLSearchParams","params","toString","console","log","defaultOptions","openReverseGeocoder","lnglat","options","opt","_extends","_lngLatToGoogle","lngLatToGoogle","x","y","Promise","resolve","_temp2","buffer","_result","VectorTile","replace","_temp","get","responseType","then","res","Buffer","from","data","_catch","error","e","reject","getTile","tile","result","layers","Object","keys","Array","isArray","geocodingResult","forEach","layerID","name","i","toGeoJSON","vt_layer","geometry","type","pointInPolygon","coordinates","_step","_iterator","_createForOfIteratorHelperLoose","done","value","getTileResult","results","muniCd","lv01Nm","gsiReverseGeocoder","_ref","lat","lon","response","_results$results","_results$results2","MuniRegex","muniMapObj","split","line","test","muniRecord","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","elevation","parseFloat","longitude","latitude","q","BaseURL"],"mappings":"uwCAQA,IAAMA,EAA2D,CAC/DC,GAAI,CACFC,SAAU,GAEVC,QAAS,yEACTC,MAAO,kBACPC,UAAW,SAAUC,GAAwB,IAAAC,EAAAC,EAS3C,MARsC,CACpCC,KACE,IAAMC,OAAOJ,EAAQK,IAAIC,OACrBF,OAAOJ,EAAQK,QACXD,OAAOJ,EAAQK,IACzBE,WAAYN,OAAFA,EAAED,EAAQQ,iBAARP,EAAAA,EAAoBM,WAChCE,KAAMP,OAAFA,EAAEF,EAAQQ,iBAARN,EAAAA,EAAoBO,KAG9B,IAKJf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AEhD7B,EAAIoC,IACzB,0EACA,CACEC,aAAc,OACdvB,OAAQ,CACN+D,IAAAA,EACAC,IAAAA,MAGLxC,KAAA,SATKyC,GAWN,IAAMiB,EAAYC,WAAWlB,EAASrC,KAAKsD,WAC3C,MAAO,CAAEE,UAAWpB,EAAKqB,SAAUtB,EAAKmB,UAAAA,EAAY,EACtD,CAAC,MAAAnD,GAAA,OAAAjB,QAAAkB,OAAAD,EAaD,CAAA,gEACEgC,EACAC,GACmC,IAAA,OAAAlD,QAAAC,gCAE/BD,QAAAC,QACmBV,EAAoB,CAAC2D,EAAKD,KAAKvC,KAAA,SAA9CW,GAEN,IAAKA,EAAOzD,KACX,MAAM,IAAIiG,MAAM,sDAGjB,OAAOxC,CAAO,2DATmBN,GAUlC,WAGC,OADA3B,QAAQC,IAAI,4EACL0D,EAAmB,CAAEE,IAAAA,EAAKC,IAAAA,GAClC,GACH,CAAC,MAAAjC,GAAA,OAAAjB,QAAAkB,OAAAD,EAED,CAAA,sDGpIM,SAAuBuD,GAAqC,IACV,OAAAxE,QAAAC,QAC/B3B,EAAAA,QAAMkC,IADdiE,yDACuB,CACpChE,aAAc,OACdvB,OAAQ,CACNsF,EAAAA,MAEF9D,cALIyC,GAQN,OADYA,EAASrC,IACV,EACb,CAAC,MAAAG,GAAA,OAAAjB,QAAAkB,OAAAD,EAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/countryOptions.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/muni.ts","../src/msearch.ts"],"sourcesContent":["import {\n ReverseGeocodingOptions,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\n\n/**\n * vector tiles settings for each country\n */\nconst countryOptions: { [s: string]: ReverseGeocodingOptions } = {\n JP: {\n zoomBase: 10,\n // tileUrl: `http://127.0.0.1:5500/docs/tiles/{z}/{x}/{y}.pbf`,\n tileUrl: 'https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf',\n layer: 'japanese-admins',\n getResult: function (feature: GeoJSON.Feature) {\n const res: ReverseGeocodingResultJP = {\n code:\n 5 === String(feature.id).length\n ? String(feature.id)\n : `0${String(feature.id)}`,\n prefecture: feature.properties?.prefecture,\n city: feature.properties?.city,\n };\n return res;\n },\n },\n};\n\n// default country options\ncountryOptions.DEFAULT = countryOptions.JP;\n\nexport default countryOptions;\n","import { lngLatToGoogle } from 'global-mercator';\nimport axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport {\n ReverseGeocodingOptions,\n ReverseGeocodingResult,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\nimport countryOptions from './countryOptions';\nimport { getTile, getTileResult } from './utils';\n\ntype LngLat = [number, number];\n\nconst api = setupCache(\n axios.create({\n timeout: 2000,\n }),\n {\n ttl: 60 * 60 * 24 * 1000, // 1 day\n }\n);\n\napi.interceptors.request.use((config) => {\n const base = config.baseURL ?? '';\n const path = config.url ?? '';\n const query = config.params\n ? `?${new URLSearchParams(config.params as Record<string, string>).toString()}`\n : '';\n const fullUrl = `${base}${path}${query}`;\n console.log('Full URL:', fullUrl);\n return config;\n});\n\nconst defaultOptions = countryOptions.DEFAULT;\n\n/**\n * Performs reverse geocoding to obtain location information based on longitude and latitude.\n *\n * @param lnglat - The longitude and latitude coordinates.\n * @param options - Optional parameters for reverse geocoding.\n * @returns A promise that resolves to the reverse geocoding result.\n */\nconst openReverseGeocoder = async (\n lnglat: LngLat,\n options?: ReverseGeocodingOptions\n): Promise<ReverseGeocodingResultJP> => {\n const opt = { ...defaultOptions, ...options };\n const [x, y] = lngLatToGoogle(lnglat, opt.zoomBase);\n const tile = await getTile(x, y, opt, api);\n const result: any = getTileResult(tile, x, y, lnglat, opt);\n return {\n results: {\n muniCd: result.code,\n lv01Nm: result.city,\n },\n code: result.code,\n prefecture: result.prefecture,\n city: result.city,\n };\n};\n\n/**\n * Performs reverse geocoding using the GSI (Geospatial Information Authority of Japan) API.\n * Given latitude and longitude coordinates, it returns the corresponding municipality code and city name.\n *\n * @param {Object} params - The parameters for the reverse geocoding request.\n * @param {number} params.lat - The latitude coordinate.\n * @param {number} params.lon - The longitude coordinate.\n * @returns {Promise<ReverseGeocodingResultJP>} A promise that resolves to an object containing the municipality code and city name.\n *\n * @example\n * const result = await gsiReverseGeocoder({ lat: 35.6895, lon: 139.6917 });\n * console.log(result); // { code: '13101', city: 'Chiyoda-ku' }\n */\nconst gsiReverseGeocoder = async ({\n lat,\n lon,\n}: {\n lat: number;\n lon: number;\n}): Promise<ReverseGeocodingResultJP> => {\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n const results = response.data;\n return {\n ...results,\n code: results?.results?.muniCd,\n city: results?.results?.lv01Nm,\n };\n};\n\n/**\n * Retrieves the elevation for a given longitude and latitude using the GSI API.\n *\n * @param {Object} coordinates - The coordinates for which to get the elevation.\n * @param {number} coordinates.lon - The longitude of the location.\n * @param {number} coordinates.lat - The latitude of the location.\n * @returns {Promise<{ longitude: number, latitude: number, elevation: number }>}\n * A promise that resolves to an object containing the longitude, latitude, and elevation.\n */\nconst getElevation = async (\n lat: number,\n lon: number\n): Promise<{ longitude: number; latitude: number; elevation: number }> => {\n // first, get elevation from GSI\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n\n const elevation = parseFloat(response.data.elevation);\n return { longitude: lon, latitude: lat, elevation };\n};\n\n/**\n * Reverse geocodes the given longitude and latitude to obtain a city code.\n *\n * @param {Object} params - The parameters for reverse geocoding.\n * @param {number} params.lon - The longitude of the location.\n * @param {number} params.lat - The latitude of the location.\n *\n * @returns {Promise<ReverseGeocodingResult>} A promise that resolves to the reverse geocoding result.\n *\n * @throws Will attempt to use an alternative geocoding service if the primary service fails.\n */\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodingResult> => {\n // first, get city code from open reverse geocoder(local)\n try {\n const result = await openReverseGeocoder([lon, lat]);\n // nếu như không thể lấy được code từ open reverse geocoder, thì sẽ lấy từ GSI\n if (!result.code) {\n throw new Error('Failed to get city code from open reverse geocoder');\n }\n\n return result;\n } catch (error) {\n // if failed, get city code from GSI\n console.log(error);\n console.log('Failed to get city code from open reverse geocoder. Try to get from GSI.');\n return gsiReverseGeocoder({ lat, lon });\n }\n};\n\nexport {\n latLonToAddress,\n getElevation,\n gsiReverseGeocoder,\n openReverseGeocoder,\n};\n","import pointInPolygon from 'point-in-polygon';\nimport axios, { AxiosInstance } from 'axios';\nimport { VectorTile } from 'mapbox-vector-tile';\nimport { ReverseGeocodingOptions, ReverseGeocodingResult } from './interfaces/index';\n\n/**\n * Get a tile from targeted country's tilesets by using x and y tile index\n * @param x x tile index\n * @param y y tile index\n * @param options ReverseGeocodingOptions\n * @param api Axios object\n * @returns VectorTile object\n */\nexport const getTile = async (\n x: number,\n y: number,\n options: ReverseGeocodingOptions,\n api: AxiosInstance = axios\n): Promise<VectorTile> => {\n const tileUrl = options.tileUrl\n .replace('{z}', String(options.zoomBase))\n .replace('{x}', String(x))\n .replace('{y}', String(y));\n\n let buffer;\n\n try {\n const res = await api.get(tileUrl, { responseType: 'arraybuffer' });\n buffer = Buffer.from(res.data, 'binary');\n } catch (error) {\n throw error;\n }\n\n const tile = new VectorTile(buffer);\n return tile;\n};\n\n/**\n * Get a result of reverse geocoding\n * @param tile VectorTile object\n * @param x x tile index\n * @param y y tile index\n * @param lnglat number[] longitude, latitude\n * @param options ReverseGeocodingOptions\n * @returns an object of result of reverse gecoding\n */\nexport const getTileResult = (\n tile: VectorTile,\n x: number,\n y: number,\n lnglat: [number, number],\n options: ReverseGeocodingOptions\n): ReverseGeocodingResult => {\n let layers = Object.keys(tile.layers);\n\n if (!Array.isArray(layers)) layers = [layers];\n\n let geocodingResult: ReverseGeocodingResult = {};\n layers.forEach((layerID) => {\n const layer = tile.layers[layerID];\n if (layer && options.layer === layer.name) {\n for (let i = 0; i < layer.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const feature: any = layer.feature(i).toGeoJSON(x, y, options.zoomBase);\n if (layers.length > 1) feature.properties.vt_layer = layerID;\n\n // Check if point is inside polygon\n // feature.geometry.coordinates is the polygon coordinates\n if (feature.geometry && feature.geometry.type === 'Polygon') {\n const coordinates = feature.geometry.coordinates[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n }\n } else if (feature.geometry && feature.geometry.type === 'MultiPolygon') {\n // Handle MultiPolygon: check if point is in any polygon\n const polygons = feature.geometry.coordinates;\n for (const polygon of polygons) {\n const coordinates = polygon[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n break;\n }\n }\n }\n }\n }\n });\n return geocodingResult;\n};\n\n","// Muni file url\nconst MuniURL = 'https://maps.gsi.go.jp/js/muni.js';\nconst MuniRegex = /GSI\\.MUNI_ARRAY\\[\"\\d+\"\\]\\s*=\\s*'(.*?)';/g;\n\nimport axios from 'axios';\n\ninterface MuniRecord {\n prefCode: string;\n prefName: string;\n cityCode: string;\n cityName: string;\n}\n\ninterface MuniMap {\n [key: string]: MuniRecord;\n}\n\ninterface AddressResults {\n muniCd: string;\n lv01Nm: string;\n mesh_code?: string;\n notes?: string;\n}\n\n/**\n * parse muni.js\n * @param muniMap\n */\nconst parseMuniMap = (muniMap: string) => {\n const muniMapObj: MuniMap = {};\n const lines = muniMap.split('\\n');\n lines.forEach((line) => {\n if (MuniRegex.test(line)) {\n const muniRecord = parseMuniRecord(line);\n muniMapObj[muniRecord.cityCode] = muniRecord;\n }\n });\n return muniMapObj;\n};\n\n/**\n * parse muni record\n * @param line\n */\nconst parseMuniRecord = (line: string) => {\n const muniRecord = line.replace(MuniRegex, '$1');\n\n const muniRecordArray = muniRecord.split(',');\n\n // validate muni record\n if (muniRecordArray.length !== 4) {\n throw new Error(`invalid muni record: ${muniRecord}`);\n }\n\n let [prefCode, prefName, cityCode, cityName] = muniRecordArray;\n\n // if cityCode is not 5 digits, add 0 to the beginning\n cityCode = cityCode.padStart(5, '0');\n\n // if prefCode is not 2 digits, add 0 to the beginning\n prefCode = prefCode.padStart(2, '0');\n\n return {\n prefCode: prefCode,\n prefName: prefName,\n cityCode: cityCode,\n cityName: cityName,\n };\n};\n\n/**\n * Fetches the municipality map data from a specified URL.\n *\n * @returns {Promise<object>} A promise that resolves to the parsed municipality map data.\n *\n * @throws Will log an error message and return an empty object if the request fails.\n */\nconst getMuniMap = async () => {\n try {\n const response = await axios.get(MuniURL, {\n responseType: 'text',\n timeout: 500,\n });\n\n const muniMap = response.data;\n return parseMuniMap(muniMap);\n } catch (error) {\n console.log(`Failed to get muni map: ${error}`);\n return {};\n }\n};\n\n/**\n * converts muni code to address name.\n *\n * @param muniMap\n * @param muniCode\n */\nconst muniCodeToAddressName = (muniMap: MuniMap, muniCode: string) => {\n const muniRecord = muniMap[muniCode];\n if (!muniRecord) {\n throw new Error(`muni code ${muniCode} not found`);\n }\n\n const add = `${muniRecord.prefName}${muniRecord.cityName}`;\n return add.replace(/ /g, '');\n};\n\n/**\n * converts address result to address name.\n * @param muniMap\n * @param addressResults\n */\nconst addressResultsToAddressName = (\n muniMap: MuniMap,\n addressResults: AddressResults\n) => {\n const mc = addressResults.muniCd;\n const muniName = muniCodeToAddressName(muniMap, mc);\n const addrName = `${muniName}${addressResults.lv01Nm}`;\n return addrName;\n};\n\nconst getMuniMapLocations = async () => {\n const muniMap = await getMuniMap();\n // muniMap is a map of all cities and wards in Japan\n // key: city code, value: { prefCode, prefName, cityCode, cityName }\n // we need to convert this to a map of all locations in Japan\n // key: prefCode , value: { prefName, cities: { key: cityCode, value: { cityCode, cityName, wards: { key: wardCode, value: { wardCode, wardName } } } } }\n\n const muniMapLocations = {};\n Object.keys(muniMap).forEach((cityCode) => {\n const muniRecord = muniMap[cityCode];\n const { prefCode, prefName, cityName } = muniRecord;\n if (!muniMapLocations[prefCode]) {\n muniMapLocations[prefCode] = { prefName, cities: {} };\n }\n\n // if cityName contains ' ', it is a ward\n // otherwise, it is a city\n if (cityName.includes(' ')) {\n // ward name is after ' '\n const [name, wardName] = cityName.split(' ');\n // find city has the same name\n const city: any = Object.values(muniMap).find(\n (c: any) => c.cityName === name\n );\n if (!city) {\n console.log(`City ${name} not found in prefCode ${prefCode}`);\n } else {\n // add ward to city\n muniMapLocations[prefCode].cities[city.cityCode].wards[cityCode] = {\n prefCode,\n cityCode: cityCode,\n cityName: `${name}${wardName}`,\n bigCityFlag: '1',\n bigCityCode: city.cityCode,\n };\n }\n } else {\n muniMapLocations[prefCode].cities[cityCode] = {\n prefCode,\n cityCode,\n cityName,\n wards: {},\n };\n }\n });\n\n // assign bigCityFlag to each city\n Object.keys(muniMapLocations).forEach((prefCode) => {\n const pref = muniMapLocations[prefCode];\n Object.keys(pref.cities).forEach((cityCode) => {\n const city = pref.cities[cityCode];\n const isBigCity = Object.values(city.wards).length > 0;\n if (isBigCity) {\n city.bigCityFlag = '2';\n } else {\n // delete wards\n delete city.wards;\n // if city is tokyo then bigCityFlag is 3, otherwise 0\n if (city.prefCode === '13') {\n city.bigCityFlag = '3';\n } else {\n city.bigCityFlag = '0';\n }\n }\n });\n });\n\n return muniMapLocations;\n};\n\nexport { getMuniMap };\n","import axios from 'axios';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\n\ntype Geometry = {\n coordinates: number[];\n type: string;\n};\n\ntype Properties = {\n addressCode: string;\n title: string;\n dataSource: string;\n};\ninterface SearchResults {\n geometry: Geometry;\n type: string;\n properties: Properties;\n}\n\n/**\n * search address by query\n */\nconst searchAddress = async (q: string): Promise<SearchResults> => {\n const url = `${BaseURL}/address-search/AddressSearch`;\n const response = await axios.get(url, {\n responseType: 'json',\n params: {\n q,\n },\n });\n\n const res = response.data;\n return res;\n};\n\nexport { searchAddress };\n"],"names":["countryOptions","JP","zoomBase","tileUrl","layer","getResult","feature","_feature$properties","_feature$properties2","code","String","id","length","prefecture","properties","city","DEFAULT","api","setupCache","axios","create","timeout","ttl","interceptors","request","use","config","_config$baseURL","_config$url","base","baseURL","path","url","query","params","URLSearchParams","toString","console","log","defaultOptions","openReverseGeocoder","lnglat","options","opt","_extends","_lngLatToGoogle","lngLatToGoogle","x","y","Promise","resolve","_temp2","buffer","_result","VectorTile","replace","_temp","get","responseType","then","res","Buffer","from","data","_catch","error","e","reject","getTile","tile","result","layers","Object","keys","Array","isArray","geocodingResult","forEach","layerID","name","i","toGeoJSON","vt_layer","geometry","type","pointInPolygon","coordinates","_step","_iterator","_createForOfIteratorHelperLoose","done","value","getTileResult","results","muniCd","lv01Nm","gsiReverseGeocoder","_ref","lat","lon","response","_results$results","_results$results2","MuniRegex","muniMapObj","split","line","test","muniRecord","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","elevation","parseFloat","longitude","latitude","q","BaseURL"],"mappings":"uwCAQA,IAAMA,EAA2D,CAC/DC,GAAI,CACFC,SAAU,GAEVC,QAAS,yEACTC,MAAO,kBACPC,UAAW,SAAUC,GAAwB,IAAAC,EAAAC,EAS3C,MARsC,CACpCC,KACE,IAAMC,OAAOJ,EAAQK,IAAIC,OACrBF,OAAOJ,EAAQK,QACXD,OAAOJ,EAAQK,IACzBE,WAAYN,OAAFA,EAAED,EAAQQ,iBAARP,EAAAA,EAAoBM,WAChCE,KAAMP,OAAFA,EAAEF,EAAQQ,iBAARN,EAAAA,EAAoBO,KAG9B,IAKJf,EAAegB,QAAUhB,EAAeC,GChBxC,IAAMgB,EAAMC,EAAAA,WACVC,EAAK,QAACC,OAAO,CACXC,QAAS,MAEX,CACEC,IAAK,QAITL,EAAIM,aAAaC,QAAQC,IAAI,SAACC,GAAUC,IAAAA,EAAAC,EAChCC,EAAqB,OAAjBF,EAAGD,EAAOI,SAAOH,EAAI,GACzBI,EAAiBH,OAAb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iB,EAAYC,WAAWlB,EAASrC,KAAKsD,WAC3C,MAAO,CAAEE,UAAWpB,EAAKqB,SAAUtB,EAAKmB,UAAAA,EAAY,EACtD,CAAC,MAAAnD,GAAA,OAAAjB,QAAAkB,OAAAD,0DAaoB,SACnBgC,EACAC,GACmC,IAAA,OAAAlD,QAAAC,gCAE/BD,QAAAC,QACmBV,EAAoB,CAAC2D,EAAKD,KAAKvC,KAA9CW,SAAAA,GAEN,IAAKA,EAAO7D,KACX,MAAM,IAAIqG,MAAM,sDAGjB,OAAOxC,CAAO,4DATmBN,CAE/B,EAQKC,SAAAA,GAIP,OAFA5B,QAAQC,IAAI2B,GACZ5B,QAAQC,IAAI,4EACL0D,EAAmB,CAAEE,IAAAA,EAAKC,IAAAA,GAClC,GACH,CAAC,MAAAjC,GAAAjB,OAAAA,QAAAkB,OAAAD,EAAA,CAAA,sDGtIK,SAAuBuD,GAAqC,IACV,OAAAxE,QAAAC,QAC/B/B,EAAAA,QAAMsC,IADdiE,yDACuB,CACpChE,aAAc,OACdxB,OAAQ,CACNuF,EAAAA,MAEF9D,cALIyC,GAQN,OADYA,EAASrC,IACV,EACb,CAAC,MAAAG,GAAA,OAAAjB,QAAAkB,OAAAD,EAAA,CAAA"}
|
package/dist/index.module.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{lngLatToGoogle as e}from"global-mercator";import r from"axios";import{setupCache as t}from"axios-cache-interceptor";import o from"point-in-polygon";import{VectorTile as n}from"mapbox-vector-tile";function
|
|
1
|
+
import{lngLatToGoogle as e}from"global-mercator";import r from"axios";import{setupCache as t}from"axios-cache-interceptor";import o from"point-in-polygon";import{VectorTile as n}from"mapbox-vector-tile";function a(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,o=Array(r);t<r;t++)o[t]=e[t];return o}function i(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return a(e,r);var t={}.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?a(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function s(){return s=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)({}).hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},s.apply(null,arguments)}var c={JP:{zoomBase:10,tileUrl:"https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf",layer:"japanese-admins",getResult:function(e){var r,t;return{code:5===String(e.id).length?String(e.id):"0"+String(e.id),prefecture:null==(r=e.properties)?void 0:r.prefecture,city:null==(t=e.properties)?void 0:t.city}}}};c.DEFAULT=c.JP;var l=t(r.create({timeout:2e3}),{ttl:864e5});l.interceptors.request.use(function(e){var r,t,o=null!=(r=e.baseURL)?r:"",n=null!=(t=e.url)?t:"",a=e.params?"?"+new URLSearchParams(e.params).toString():"";return console.log("Full URL:",""+o+n+a),e});var u=c.DEFAULT,m=function(t,a){try{var c=s({},u,a),m=e(t,c.zoomBase),p=m[0],f=m[1];return Promise.resolve(function(e,t,o,a){void 0===a&&(a=r);try{var i,s=function(e){return new n(i)},c=o.tileUrl.replace("{z}",String(o.zoomBase)).replace("{x}",String(e)).replace("{y}",String(t)),l=function(e,r){try{var t=Promise.resolve(a.get(c,{responseType:"arraybuffer"})).then(function(e){i=Buffer.from(e.data,"binary")})}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(0,function(e){throw e});return Promise.resolve(l&&l.then?l.then(s):s())}catch(e){return Promise.reject(e)}}(p,f,c,l)).then(function(e){var r=function(e,r,t,n,a){var s=Object.keys(e.layers);Array.isArray(s)||(s=[s]);var c={};return s.forEach(function(l){var u=e.layers[l];if(u&&a.layer===u.name)for(var m=0;m<u.length;m++){var p=u.feature(m).toGeoJSON(r,t,a.zoomBase);if(s.length>1&&(p.properties.vt_layer=l),p.geometry&&"Polygon"===p.geometry.type)o(n,p.geometry.coordinates[0])&&(c=a.getResult(p));else if(p.geometry&&"MultiPolygon"===p.geometry.type)for(var f,g=i(p.geometry.coordinates);!(f=g()).done;)if(o(n,f.value[0])){c=a.getResult(p);break}}}),c}(e,p,f,t,c);return{results:{muniCd:r.code,lv01Nm:r.city},code:r.code,prefecture:r.prefecture,city:r.city}})}catch(e){return Promise.reject(e)}},p=function(e){var r=e.lat,t=e.lon;try{return Promise.resolve(l.get("https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress",{responseType:"json",params:{lat:r,lon:t}})).then(function(e){var r,t,o=e.data;return s({},o,{code:null==o||null==(r=o.results)?void 0:r.muniCd,city:null==o||null==(t=o.results)?void 0:t.lv01Nm})})}catch(e){return Promise.reject(e)}},f=function(e,r){try{return Promise.resolve(l.get("https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php",{responseType:"json",params:{lat:e,lon:r}})).then(function(t){var o=parseFloat(t.data.elevation);return{longitude:r,latitude:e,elevation:o}})}catch(e){return Promise.reject(e)}},g=function(e,r){try{return Promise.resolve(function(t,o){try{var n=Promise.resolve(m([r,e])).then(function(e){if(!e.code)throw new Error("Failed to get city code from open reverse geocoder");return e})}catch(e){return o(e)}return n&&n.then?n.then(void 0,o):n}(0,function(t){return console.log(t),console.log("Failed to get city code from open reverse geocoder. Try to get from GSI."),p({lat:e,lon:r})}))}catch(e){return Promise.reject(e)}},v=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g,d=function(){try{return Promise.resolve(function(e,t){try{var o=Promise.resolve(r.get("https://maps.gsi.go.jp/js/muni.js",{responseType:"text",timeout:500})).then(function(e){return r={},e.data.split("\n").forEach(function(e){if(v.test(e)){var t=function(e){var r=e.replace(v,"$1"),t=r.split(",");if(4!==t.length)throw new Error("invalid muni record: "+r);var o=t[0],n=t[1],a=t[2],i=t[3];return a=a.padStart(5,"0"),{prefCode:o=o.padStart(2,"0"),prefName:n,cityCode:a,cityName:i}}(e);r[t.cityCode]=t}}),r;var r})}catch(e){return t(e)}return o&&o.then?o.then(void 0,t):o}(0,function(e){return console.log("Failed to get muni map: "+e),{}}))}catch(e){return Promise.reject(e)}},y=function(e){try{return Promise.resolve(r.get("https://msearch.gsi.go.jp/address-search/AddressSearch",{responseType:"json",params:{q:e}})).then(function(e){return e.data})}catch(e){return Promise.reject(e)}};export{d as getCityMap,f as getElevation,p as gsiReverseGeocoder,g as latLonToAddress,m as openReverseGeocoder,y as searchAddress};
|
|
2
2
|
//# sourceMappingURL=index.module.js.map
|
package/dist/index.module.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.module.js","sources":["../src/countryOptions.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/muni.ts","../src/msearch.ts"],"sourcesContent":["import {\n ReverseGeocodingOptions,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\n\n/**\n * vector tiles settings for each country\n */\nconst countryOptions: { [s: string]: ReverseGeocodingOptions } = {\n JP: {\n zoomBase: 10,\n // tileUrl: `http://127.0.0.1:5500/docs/tiles/{z}/{x}/{y}.pbf`,\n tileUrl: 'https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf',\n layer: 'japanese-admins',\n getResult: function (feature: GeoJSON.Feature) {\n const res: ReverseGeocodingResultJP = {\n code:\n 5 === String(feature.id).length\n ? String(feature.id)\n : `0${String(feature.id)}`,\n prefecture: feature.properties?.prefecture,\n city: feature.properties?.city,\n };\n return res;\n },\n },\n};\n\n// default country options\ncountryOptions.DEFAULT = countryOptions.JP;\n\nexport default countryOptions;\n","import { lngLatToGoogle } from 'global-mercator';\nimport axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport {\n ReverseGeocodingOptions,\n ReverseGeocodingResult,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\nimport countryOptions from './countryOptions';\nimport { getTile, getTileResult } from './utils';\n\ntype LngLat = [number, number];\n\nconst api = setupCache(\n axios.create({\n timeout: 2000,\n }),\n {\n ttl: 60 * 60 * 24 * 1000, // 1 day\n }\n);\n\napi.interceptors.request.use((config) => {\n const fullUrl = `${config.baseURL}${config.url}?${new URLSearchParams(\n config.params\n ).toString()}`;\n console.log('Full URL:', fullUrl);\n return config;\n});\n\nconst defaultOptions = countryOptions.DEFAULT;\n\n/**\n * Performs reverse geocoding to obtain location information based on longitude and latitude.\n *\n * @param lnglat - The longitude and latitude coordinates.\n * @param options - Optional parameters for reverse geocoding.\n * @returns A promise that resolves to the reverse geocoding result.\n */\nconst openReverseGeocoder = async (\n lnglat: LngLat,\n options?: ReverseGeocodingOptions\n): Promise<ReverseGeocodingResultJP> => {\n const opt = { ...defaultOptions, ...options };\n const [x, y] = lngLatToGoogle(lnglat, opt.zoomBase);\n const tile = await getTile(x, y, opt, api);\n const result: any = getTileResult(tile, x, y, lnglat, opt);\n return {\n results: {\n muniCd: result.code,\n lv01Nm: result.city,\n },\n code: result.code,\n prefecture: result.prefecture,\n city: result.city,\n };\n};\n\n/**\n * Performs reverse geocoding using the GSI (Geospatial Information Authority of Japan) API.\n * Given latitude and longitude coordinates, it returns the corresponding municipality code and city name.\n *\n * @param {Object} params - The parameters for the reverse geocoding request.\n * @param {number} params.lat - The latitude coordinate.\n * @param {number} params.lon - The longitude coordinate.\n * @returns {Promise<ReverseGeocodingResultJP>} A promise that resolves to an object containing the municipality code and city name.\n *\n * @example\n * const result = await gsiReverseGeocoder({ lat: 35.6895, lon: 139.6917 });\n * console.log(result); // { code: '13101', city: 'Chiyoda-ku' }\n */\nconst gsiReverseGeocoder = async ({\n lat,\n lon,\n}: {\n lat: number;\n lon: number;\n}): Promise<ReverseGeocodingResultJP> => {\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n const results = response.data;\n return {\n ...results,\n code: results?.results?.muniCd,\n city: results?.results?.lv01Nm,\n };\n};\n\n/**\n * Retrieves the elevation for a given longitude and latitude using the GSI API.\n *\n * @param {Object} coordinates - The coordinates for which to get the elevation.\n * @param {number} coordinates.lon - The longitude of the location.\n * @param {number} coordinates.lat - The latitude of the location.\n * @returns {Promise<{ longitude: number, latitude: number, elevation: number }>}\n * A promise that resolves to an object containing the longitude, latitude, and elevation.\n */\nconst getElevation = async (\n lat: number,\n lon: number\n): Promise<{ longitude: number; latitude: number; elevation: number }> => {\n // first, get elevation from GSI\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n\n const elevation = parseFloat(response.data.elevation);\n return { longitude: lon, latitude: lat, elevation };\n};\n\n/**\n * Reverse geocodes the given longitude and latitude to obtain a city code.\n *\n * @param {Object} params - The parameters for reverse geocoding.\n * @param {number} params.lon - The longitude of the location.\n * @param {number} params.lat - The latitude of the location.\n *\n * @returns {Promise<ReverseGeocodingResult>} A promise that resolves to the reverse geocoding result.\n *\n * @throws Will attempt to use an alternative geocoding service if the primary service fails.\n */\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodingResult> => {\n // first, get city code from open reverse geocoder(local)\n try {\n const result = await openReverseGeocoder([lon, lat]);\n // nếu như không thể lấy được code từ open reverse geocoder, thì sẽ lấy từ GSI\n if (!result.code) {\n throw new Error('Failed to get city code from open reverse geocoder');\n }\n\n return result;\n } catch (error) {\n // if failed, get city code from GSI\n console.log('Failed to get city code from open reverse geocoder. Try to get from GSI.');\n return gsiReverseGeocoder({ lat, lon });\n }\n};\n\nexport {\n latLonToAddress,\n getElevation,\n gsiReverseGeocoder,\n openReverseGeocoder,\n};\n","import pointInPolygon from 'point-in-polygon';\nimport axios, { AxiosInstance } from 'axios';\nimport { VectorTile } from 'mapbox-vector-tile';\nimport { ReverseGeocodingOptions, ReverseGeocodingResult } from './interfaces/index';\n\n/**\n * Get a tile from targeted country's tilesets by using x and y tile index\n * @param x x tile index\n * @param y y tile index\n * @param options ReverseGeocodingOptions\n * @param api Axios object\n * @returns VectorTile object\n */\nexport const getTile = async (\n x: number,\n y: number,\n options: ReverseGeocodingOptions,\n api: AxiosInstance = axios\n): Promise<VectorTile> => {\n const tileUrl = options.tileUrl\n .replace('{z}', String(options.zoomBase))\n .replace('{x}', String(x))\n .replace('{y}', String(y));\n\n let buffer;\n\n try {\n const res = await api.get(tileUrl, { responseType: 'arraybuffer' });\n buffer = Buffer.from(res.data, 'binary');\n } catch (error) {\n throw error;\n }\n\n const tile = new VectorTile(buffer);\n return tile;\n};\n\n/**\n * Get a result of reverse geocoding\n * @param tile VectorTile object\n * @param x x tile index\n * @param y y tile index\n * @param lnglat number[] longitude, latitude\n * @param options ReverseGeocodingOptions\n * @returns an object of result of reverse gecoding\n */\nexport const getTileResult = (\n tile: VectorTile,\n x: number,\n y: number,\n lnglat: [number, number],\n options: ReverseGeocodingOptions\n): ReverseGeocodingResult => {\n let layers = Object.keys(tile.layers);\n\n if (!Array.isArray(layers)) layers = [layers];\n\n let geocodingResult: ReverseGeocodingResult = {};\n layers.forEach((layerID) => {\n const layer = tile.layers[layerID];\n if (layer && options.layer === layer.name) {\n for (let i = 0; i < layer.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const feature: any = layer.feature(i).toGeoJSON(x, y, options.zoomBase);\n if (layers.length > 1) feature.properties.vt_layer = layerID;\n\n // Check if point is inside polygon\n // feature.geometry.coordinates is the polygon coordinates\n if (feature.geometry && feature.geometry.type === 'Polygon') {\n const coordinates = feature.geometry.coordinates[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n }\n } else if (feature.geometry && feature.geometry.type === 'MultiPolygon') {\n // Handle MultiPolygon: check if point is in any polygon\n const polygons = feature.geometry.coordinates;\n for (const polygon of polygons) {\n const coordinates = polygon[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n break;\n }\n }\n }\n }\n }\n });\n return geocodingResult;\n};\n\n","// Muni file url\nconst MuniURL = 'https://maps.gsi.go.jp/js/muni.js';\nconst MuniRegex = /GSI\\.MUNI_ARRAY\\[\"\\d+\"\\]\\s*=\\s*'(.*?)';/g;\n\nimport axios from 'axios';\n\ninterface MuniRecord {\n prefCode: string;\n prefName: string;\n cityCode: string;\n cityName: string;\n}\n\ninterface MuniMap {\n [key: string]: MuniRecord;\n}\n\ninterface AddressResults {\n muniCd: string;\n lv01Nm: string;\n mesh_code?: string;\n notes?: string;\n}\n\n/**\n * parse muni.js\n * @param muniMap\n */\nconst parseMuniMap = (muniMap: string) => {\n const muniMapObj: MuniMap = {};\n const lines = muniMap.split('\\n');\n lines.forEach((line) => {\n if (MuniRegex.test(line)) {\n const muniRecord = parseMuniRecord(line);\n muniMapObj[muniRecord.cityCode] = muniRecord;\n }\n });\n return muniMapObj;\n};\n\n/**\n * parse muni record\n * @param line\n */\nconst parseMuniRecord = (line: string) => {\n const muniRecord = line.replace(MuniRegex, '$1');\n\n const muniRecordArray = muniRecord.split(',');\n\n // validate muni record\n if (muniRecordArray.length !== 4) {\n throw new Error(`invalid muni record: ${muniRecord}`);\n }\n\n let [prefCode, prefName, cityCode, cityName] = muniRecordArray;\n\n // if cityCode is not 5 digits, add 0 to the beginning\n cityCode = cityCode.padStart(5, '0');\n\n // if prefCode is not 2 digits, add 0 to the beginning\n prefCode = prefCode.padStart(2, '0');\n\n return {\n prefCode: prefCode,\n prefName: prefName,\n cityCode: cityCode,\n cityName: cityName,\n };\n};\n\n/**\n * Fetches the municipality map data from a specified URL.\n *\n * @returns {Promise<object>} A promise that resolves to the parsed municipality map data.\n *\n * @throws Will log an error message and return an empty object if the request fails.\n */\nconst getMuniMap = async () => {\n try {\n const response = await axios.get(MuniURL, {\n responseType: 'text',\n timeout: 500,\n });\n\n const muniMap = response.data;\n return parseMuniMap(muniMap);\n } catch (error) {\n console.log(`Failed to get muni map: ${error}`);\n return {};\n }\n};\n\n/**\n * converts muni code to address name.\n *\n * @param muniMap\n * @param muniCode\n */\nconst muniCodeToAddressName = (muniMap: MuniMap, muniCode: string) => {\n const muniRecord = muniMap[muniCode];\n if (!muniRecord) {\n throw new Error(`muni code ${muniCode} not found`);\n }\n\n const add = `${muniRecord.prefName}${muniRecord.cityName}`;\n return add.replace(/ /g, '');\n};\n\n/**\n * converts address result to address name.\n * @param muniMap\n * @param addressResults\n */\nconst addressResultsToAddressName = (\n muniMap: MuniMap,\n addressResults: AddressResults\n) => {\n const mc = addressResults.muniCd;\n const muniName = muniCodeToAddressName(muniMap, mc);\n const addrName = `${muniName}${addressResults.lv01Nm}`;\n return addrName;\n};\n\nconst getMuniMapLocations = async () => {\n const muniMap = await getMuniMap();\n // muniMap is a map of all cities and wards in Japan\n // key: city code, value: { prefCode, prefName, cityCode, cityName }\n // we need to convert this to a map of all locations in Japan\n // key: prefCode , value: { prefName, cities: { key: cityCode, value: { cityCode, cityName, wards: { key: wardCode, value: { wardCode, wardName } } } } }\n\n const muniMapLocations = {};\n Object.keys(muniMap).forEach((cityCode) => {\n const muniRecord = muniMap[cityCode];\n const { prefCode, prefName, cityName } = muniRecord;\n if (!muniMapLocations[prefCode]) {\n muniMapLocations[prefCode] = { prefName, cities: {} };\n }\n\n // if cityName contains ' ', it is a ward\n // otherwise, it is a city\n if (cityName.includes(' ')) {\n // ward name is after ' '\n const [name, wardName] = cityName.split(' ');\n // find city has the same name\n const city: any = Object.values(muniMap).find(\n (c: any) => c.cityName === name\n );\n if (!city) {\n console.log(`City ${name} not found in prefCode ${prefCode}`);\n } else {\n // add ward to city\n muniMapLocations[prefCode].cities[city.cityCode].wards[cityCode] = {\n prefCode,\n cityCode: cityCode,\n cityName: `${name}${wardName}`,\n bigCityFlag: '1',\n bigCityCode: city.cityCode,\n };\n }\n } else {\n muniMapLocations[prefCode].cities[cityCode] = {\n prefCode,\n cityCode,\n cityName,\n wards: {},\n };\n }\n });\n\n // assign bigCityFlag to each city\n Object.keys(muniMapLocations).forEach((prefCode) => {\n const pref = muniMapLocations[prefCode];\n Object.keys(pref.cities).forEach((cityCode) => {\n const city = pref.cities[cityCode];\n const isBigCity = Object.values(city.wards).length > 0;\n if (isBigCity) {\n city.bigCityFlag = '2';\n } else {\n // delete wards\n delete city.wards;\n // if city is tokyo then bigCityFlag is 3, otherwise 0\n if (city.prefCode === '13') {\n city.bigCityFlag = '3';\n } else {\n city.bigCityFlag = '0';\n }\n }\n });\n });\n\n return muniMapLocations;\n};\n\nexport { getMuniMap };\n","import axios from 'axios';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\n\ntype Geometry = {\n coordinates: number[];\n type: string;\n};\n\ntype Properties = {\n addressCode: string;\n title: string;\n dataSource: string;\n};\ninterface SearchResults {\n geometry: Geometry;\n type: string;\n properties: Properties;\n}\n\n/**\n * search address by query\n */\nconst searchAddress = async (q: string): Promise<SearchResults> => {\n const url = `${BaseURL}/address-search/AddressSearch`;\n const response = await axios.get(url, {\n responseType: 'json',\n params: {\n q,\n },\n });\n\n const res = response.data;\n return res;\n};\n\nexport { searchAddress };\n"],"names":["countryOptions","JP","zoomBase","tileUrl","layer","getResult","feature","_feature$properties","_feature$properties2","code","String","id","length","prefecture","properties","city","DEFAULT","api","setupCache","axios","create","timeout","ttl","interceptors","request","use","config","fullUrl","baseURL","url","URLSearchParams","params","toString","console","log","defaultOptions","openReverseGeocoder","lnglat","options","opt","_extends","_lngLatToGoogle","lngLatToGoogle","x","y","Promise","resolve","_temp2","buffer","_result","VectorTile","replace","_temp","get","responseType","then","res","Buffer","from","data","_catch","error","e","reject","getTile","tile","result","layers","Object","keys","Array","isArray","geocodingResult","forEach","layerID","name","i","toGeoJSON","vt_layer","geometry","type","pointInPolygon","coordinates","_step","_iterator","_createForOfIteratorHelperLoose","done","value","getTileResult","results","muniCd","lv01Nm","gsiReverseGeocoder","_ref","lat","lon","response","_results$results","_results$results2","getElevation","elevation","parseFloat","longitude","latitude","latLonToAddress","Error","MuniRegex","getMuniMap","muniMapObj","split","line","test","muniRecord","muniRecordArray","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","searchAddress","q","BaseURL"],"mappings":"usCAQA,IAAMA,EAA2D,CAC/DC,GAAI,CACFC,SAAU,GAEVC,QAAS,yEACTC,MAAO,kBACPC,UAAW,SAAUC,GAAwB,IAAAC,EAAAC,EAS3C,MARsC,CACpCC,KACE,IAAMC,OAAOJ,EAAQK,IAAIC,OACrBF,OAAOJ,EAAQK,QACXD,OAAOJ,EAAQK,IACzBE,WAAYN,OAAFA,EAAED,EAAQQ,iBAARP,EAAAA,EAAoBM,WAChCE,KAAMP,OAAFA,EAAEF,EAAQQ,iBAARN,EAAAA,EAAoBO,KAG9B,IAKJf,EAAegB,QAAUhB,EAAeC,GChBxC,IAAMgB,EAAMC,EACVC,EAAMC,OAAO,CACXC,QAAS,MAEX,CACEC,IAAK,QAITL,EAAIM,aAAaC,QAAQC,IAAI,SAACC,GAC5B,IAAMC,EAAO,GAAMD,EAAOE,QAAUF,EAAOG,IAAO,IAAA,IAAIC,gBACpDJ,EAAOK,QACPC,WAEF,OADAC,QAAQC,IAAI,YAAaP,GAClBD,CACT,GAEA,IAAMS,EAAiBnC,EAAegB,QAShCoB,EAAmB,SACvBC,EACAC,GACqC,IACrC,IAAMC,EAAGC,EAAA,CAAA,EAAQL,EAAmBG,GACpCG,EAAeC,EAAeL,EAAQE,EAAIrC,UAAnCyC,EAACF,EAAA,GAAEG,EAACH,EAAyC,GAAA,OAAAI,QAAAC,QC/BzC,SACXH,EACAC,EACAN,EACArB,QAAqB,IAArBA,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CAAC,MAAAC,GAAA,OAAAjB,QAAAkB,OAAAD,EAAA,CAAA,EClEK0D,EAAA,SAAuBC,GAAqC,IACV,OAAA5E,QAAAC,QAC/B3B,EAAMkC,IADdqE,yDACuB,CACpCpE,aAAc,OACdvB,OAAQ,CACN0F,EAAAA,MAEFlE,cALIyC,GAQN,OADYA,EAASrC,IACV,EACb,CAAC,MAAAG,GAAA,OAAAjB,QAAAkB,OAAAD,EAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.module.js","sources":["../src/countryOptions.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/muni.ts","../src/msearch.ts"],"sourcesContent":["import {\n ReverseGeocodingOptions,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\n\n/**\n * vector tiles settings for each country\n */\nconst countryOptions: { [s: string]: ReverseGeocodingOptions } = {\n JP: {\n zoomBase: 10,\n // tileUrl: `http://127.0.0.1:5500/docs/tiles/{z}/{x}/{y}.pbf`,\n tileUrl: 'https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf',\n layer: 'japanese-admins',\n getResult: function (feature: GeoJSON.Feature) {\n const res: ReverseGeocodingResultJP = {\n code:\n 5 === String(feature.id).length\n ? String(feature.id)\n : `0${String(feature.id)}`,\n prefecture: feature.properties?.prefecture,\n city: feature.properties?.city,\n };\n return res;\n },\n },\n};\n\n// default country options\ncountryOptions.DEFAULT = countryOptions.JP;\n\nexport default countryOptions;\n","import { lngLatToGoogle } from 'global-mercator';\nimport axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport {\n ReverseGeocodingOptions,\n ReverseGeocodingResult,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\nimport countryOptions from './countryOptions';\nimport { getTile, getTileResult } from './utils';\n\ntype LngLat = [number, number];\n\nconst api = setupCache(\n axios.create({\n timeout: 2000,\n }),\n {\n ttl: 60 * 60 * 24 * 1000, // 1 day\n }\n);\n\napi.interceptors.request.use((config) => {\n const base = config.baseURL ?? '';\n const path = config.url ?? '';\n const query = config.params\n ? `?${new URLSearchParams(config.params as Record<string, string>).toString()}`\n : '';\n const fullUrl = `${base}${path}${query}`;\n console.log('Full URL:', fullUrl);\n return config;\n});\n\nconst defaultOptions = countryOptions.DEFAULT;\n\n/**\n * Performs reverse geocoding to obtain location information based on longitude and latitude.\n *\n * @param lnglat - The longitude and latitude coordinates.\n * @param options - Optional parameters for reverse geocoding.\n * @returns A promise that resolves to the reverse geocoding result.\n */\nconst openReverseGeocoder = async (\n lnglat: LngLat,\n options?: ReverseGeocodingOptions\n): Promise<ReverseGeocodingResultJP> => {\n const opt = { ...defaultOptions, ...options };\n const [x, y] = lngLatToGoogle(lnglat, opt.zoomBase);\n const tile = await getTile(x, y, opt, api);\n const result: any = getTileResult(tile, x, y, lnglat, opt);\n return {\n results: {\n muniCd: result.code,\n lv01Nm: result.city,\n },\n code: result.code,\n prefecture: result.prefecture,\n city: result.city,\n };\n};\n\n/**\n * Performs reverse geocoding using the GSI (Geospatial Information Authority of Japan) API.\n * Given latitude and longitude coordinates, it returns the corresponding municipality code and city name.\n *\n * @param {Object} params - The parameters for the reverse geocoding request.\n * @param {number} params.lat - The latitude coordinate.\n * @param {number} params.lon - The longitude coordinate.\n * @returns {Promise<ReverseGeocodingResultJP>} A promise that resolves to an object containing the municipality code and city name.\n *\n * @example\n * const result = await gsiReverseGeocoder({ lat: 35.6895, lon: 139.6917 });\n * console.log(result); // { code: '13101', city: 'Chiyoda-ku' }\n */\nconst gsiReverseGeocoder = async ({\n lat,\n lon,\n}: {\n lat: number;\n lon: number;\n}): Promise<ReverseGeocodingResultJP> => {\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n const results = response.data;\n return {\n ...results,\n code: results?.results?.muniCd,\n city: results?.results?.lv01Nm,\n };\n};\n\n/**\n * Retrieves the elevation for a given longitude and latitude using the GSI API.\n *\n * @param {Object} coordinates - The coordinates for which to get the elevation.\n * @param {number} coordinates.lon - The longitude of the location.\n * @param {number} coordinates.lat - The latitude of the location.\n * @returns {Promise<{ longitude: number, latitude: number, elevation: number }>}\n * A promise that resolves to an object containing the longitude, latitude, and elevation.\n */\nconst getElevation = async (\n lat: number,\n lon: number\n): Promise<{ longitude: number; latitude: number; elevation: number }> => {\n // first, get elevation from GSI\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n\n const elevation = parseFloat(response.data.elevation);\n return { longitude: lon, latitude: lat, elevation };\n};\n\n/**\n * Reverse geocodes the given longitude and latitude to obtain a city code.\n *\n * @param {Object} params - The parameters for reverse geocoding.\n * @param {number} params.lon - The longitude of the location.\n * @param {number} params.lat - The latitude of the location.\n *\n * @returns {Promise<ReverseGeocodingResult>} A promise that resolves to the reverse geocoding result.\n *\n * @throws Will attempt to use an alternative geocoding service if the primary service fails.\n */\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodingResult> => {\n // first, get city code from open reverse geocoder(local)\n try {\n const result = await openReverseGeocoder([lon, lat]);\n // nếu như không thể lấy được code từ open reverse geocoder, thì sẽ lấy từ GSI\n if (!result.code) {\n throw new Error('Failed to get city code from open reverse geocoder');\n }\n\n return result;\n } catch (error) {\n // if failed, get city code from GSI\n console.log(error);\n console.log('Failed to get city code from open reverse geocoder. Try to get from GSI.');\n return gsiReverseGeocoder({ lat, lon });\n }\n};\n\nexport {\n latLonToAddress,\n getElevation,\n gsiReverseGeocoder,\n openReverseGeocoder,\n};\n","import pointInPolygon from 'point-in-polygon';\nimport axios, { AxiosInstance } from 'axios';\nimport { VectorTile } from 'mapbox-vector-tile';\nimport { ReverseGeocodingOptions, ReverseGeocodingResult } from './interfaces/index';\n\n/**\n * Get a tile from targeted country's tilesets by using x and y tile index\n * @param x x tile index\n * @param y y tile index\n * @param options ReverseGeocodingOptions\n * @param api Axios object\n * @returns VectorTile object\n */\nexport const getTile = async (\n x: number,\n y: number,\n options: ReverseGeocodingOptions,\n api: AxiosInstance = axios\n): Promise<VectorTile> => {\n const tileUrl = options.tileUrl\n .replace('{z}', String(options.zoomBase))\n .replace('{x}', String(x))\n .replace('{y}', String(y));\n\n let buffer;\n\n try {\n const res = await api.get(tileUrl, { responseType: 'arraybuffer' });\n buffer = Buffer.from(res.data, 'binary');\n } catch (error) {\n throw error;\n }\n\n const tile = new VectorTile(buffer);\n return tile;\n};\n\n/**\n * Get a result of reverse geocoding\n * @param tile VectorTile object\n * @param x x tile index\n * @param y y tile index\n * @param lnglat number[] longitude, latitude\n * @param options ReverseGeocodingOptions\n * @returns an object of result of reverse gecoding\n */\nexport const getTileResult = (\n tile: VectorTile,\n x: number,\n y: number,\n lnglat: [number, number],\n options: ReverseGeocodingOptions\n): ReverseGeocodingResult => {\n let layers = Object.keys(tile.layers);\n\n if (!Array.isArray(layers)) layers = [layers];\n\n let geocodingResult: ReverseGeocodingResult = {};\n layers.forEach((layerID) => {\n const layer = tile.layers[layerID];\n if (layer && options.layer === layer.name) {\n for (let i = 0; i < layer.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const feature: any = layer.feature(i).toGeoJSON(x, y, options.zoomBase);\n if (layers.length > 1) feature.properties.vt_layer = layerID;\n\n // Check if point is inside polygon\n // feature.geometry.coordinates is the polygon coordinates\n if (feature.geometry && feature.geometry.type === 'Polygon') {\n const coordinates = feature.geometry.coordinates[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n }\n } else if (feature.geometry && feature.geometry.type === 'MultiPolygon') {\n // Handle MultiPolygon: check if point is in any polygon\n const polygons = feature.geometry.coordinates;\n for (const polygon of polygons) {\n const coordinates = polygon[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n break;\n }\n }\n }\n }\n }\n });\n return geocodingResult;\n};\n\n","// Muni file url\nconst MuniURL = 'https://maps.gsi.go.jp/js/muni.js';\nconst MuniRegex = /GSI\\.MUNI_ARRAY\\[\"\\d+\"\\]\\s*=\\s*'(.*?)';/g;\n\nimport axios from 'axios';\n\ninterface MuniRecord {\n prefCode: string;\n prefName: string;\n cityCode: string;\n cityName: string;\n}\n\ninterface MuniMap {\n [key: string]: MuniRecord;\n}\n\ninterface AddressResults {\n muniCd: string;\n lv01Nm: string;\n mesh_code?: string;\n notes?: string;\n}\n\n/**\n * parse muni.js\n * @param muniMap\n */\nconst parseMuniMap = (muniMap: string) => {\n const muniMapObj: MuniMap = {};\n const lines = muniMap.split('\\n');\n lines.forEach((line) => {\n if (MuniRegex.test(line)) {\n const muniRecord = parseMuniRecord(line);\n muniMapObj[muniRecord.cityCode] = muniRecord;\n }\n });\n return muniMapObj;\n};\n\n/**\n * parse muni record\n * @param line\n */\nconst parseMuniRecord = (line: string) => {\n const muniRecord = line.replace(MuniRegex, '$1');\n\n const muniRecordArray = muniRecord.split(',');\n\n // validate muni record\n if (muniRecordArray.length !== 4) {\n throw new Error(`invalid muni record: ${muniRecord}`);\n }\n\n let [prefCode, prefName, cityCode, cityName] = muniRecordArray;\n\n // if cityCode is not 5 digits, add 0 to the beginning\n cityCode = cityCode.padStart(5, '0');\n\n // if prefCode is not 2 digits, add 0 to the beginning\n prefCode = prefCode.padStart(2, '0');\n\n return {\n prefCode: prefCode,\n prefName: prefName,\n cityCode: cityCode,\n cityName: cityName,\n };\n};\n\n/**\n * Fetches the municipality map data from a specified URL.\n *\n * @returns {Promise<object>} A promise that resolves to the parsed municipality map data.\n *\n * @throws Will log an error message and return an empty object if the request fails.\n */\nconst getMuniMap = async () => {\n try {\n const response = await axios.get(MuniURL, {\n responseType: 'text',\n timeout: 500,\n });\n\n const muniMap = response.data;\n return parseMuniMap(muniMap);\n } catch (error) {\n console.log(`Failed to get muni map: ${error}`);\n return {};\n }\n};\n\n/**\n * converts muni code to address name.\n *\n * @param muniMap\n * @param muniCode\n */\nconst muniCodeToAddressName = (muniMap: MuniMap, muniCode: string) => {\n const muniRecord = muniMap[muniCode];\n if (!muniRecord) {\n throw new Error(`muni code ${muniCode} not found`);\n }\n\n const add = `${muniRecord.prefName}${muniRecord.cityName}`;\n return add.replace(/ /g, '');\n};\n\n/**\n * converts address result to address name.\n * @param muniMap\n * @param addressResults\n */\nconst addressResultsToAddressName = (\n muniMap: MuniMap,\n addressResults: AddressResults\n) => {\n const mc = addressResults.muniCd;\n const muniName = muniCodeToAddressName(muniMap, mc);\n const addrName = `${muniName}${addressResults.lv01Nm}`;\n return addrName;\n};\n\nconst getMuniMapLocations = async () => {\n const muniMap = await getMuniMap();\n // muniMap is a map of all cities and wards in Japan\n // key: city code, value: { prefCode, prefName, cityCode, cityName }\n // we need to convert this to a map of all locations in Japan\n // key: prefCode , value: { prefName, cities: { key: cityCode, value: { cityCode, cityName, wards: { key: wardCode, value: { wardCode, wardName } } } } }\n\n const muniMapLocations = {};\n Object.keys(muniMap).forEach((cityCode) => {\n const muniRecord = muniMap[cityCode];\n const { prefCode, prefName, cityName } = muniRecord;\n if (!muniMapLocations[prefCode]) {\n muniMapLocations[prefCode] = { prefName, cities: {} };\n }\n\n // if cityName contains ' ', it is a ward\n // otherwise, it is a city\n if (cityName.includes(' ')) {\n // ward name is after ' '\n const [name, wardName] = cityName.split(' ');\n // find city has the same name\n const city: any = Object.values(muniMap).find(\n (c: any) => c.cityName === name\n );\n if (!city) {\n console.log(`City ${name} not found in prefCode ${prefCode}`);\n } else {\n // add ward to city\n muniMapLocations[prefCode].cities[city.cityCode].wards[cityCode] = {\n prefCode,\n cityCode: cityCode,\n cityName: `${name}${wardName}`,\n bigCityFlag: '1',\n bigCityCode: city.cityCode,\n };\n }\n } else {\n muniMapLocations[prefCode].cities[cityCode] = {\n prefCode,\n cityCode,\n cityName,\n wards: {},\n };\n }\n });\n\n // assign bigCityFlag to each city\n Object.keys(muniMapLocations).forEach((prefCode) => {\n const pref = muniMapLocations[prefCode];\n Object.keys(pref.cities).forEach((cityCode) => {\n const city = pref.cities[cityCode];\n const isBigCity = Object.values(city.wards).length > 0;\n if (isBigCity) {\n city.bigCityFlag = '2';\n } else {\n // delete wards\n delete city.wards;\n // if city is tokyo then bigCityFlag is 3, otherwise 0\n if (city.prefCode === '13') {\n city.bigCityFlag = '3';\n } else {\n city.bigCityFlag = '0';\n }\n }\n });\n });\n\n return muniMapLocations;\n};\n\nexport { getMuniMap };\n","import axios from 'axios';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\n\ntype Geometry = {\n coordinates: number[];\n type: string;\n};\n\ntype Properties = {\n addressCode: string;\n title: string;\n dataSource: string;\n};\ninterface SearchResults {\n geometry: Geometry;\n type: string;\n properties: Properties;\n}\n\n/**\n * search address by query\n */\nconst searchAddress = async (q: string): Promise<SearchResults> => {\n const url = `${BaseURL}/address-search/AddressSearch`;\n const response = await axios.get(url, {\n responseType: 'json',\n params: {\n q,\n },\n });\n\n const res = response.data;\n return res;\n};\n\nexport { searchAddress };\n"],"names":["countryOptions","JP","zoomBase","tileUrl","layer","getResult","feature","_feature$properties","_feature$properties2","code","String","id","length","prefecture","properties","city","DEFAULT","api","setupCache","axios","create","timeout","ttl","interceptors","request","use","config","_config$baseURL","_config$url","base","baseURL","path","url","query","params","URLSearchParams","toString","console","log","defaultOptions","openReverseGeocoder","lnglat","options","opt","_extends","_lngLatToGoogle","lngLatToGoogle","x","y","Promise","resolve","_temp2","buffer","_result","VectorTile","replace","_temp","get","responseType","then","res","Buffer","from","data","_catch","error","e","reject","getTile","tile","result","layers","Object","keys","Array","isArray","geocodingResult","forEach","layerID","name","i","toGeoJSON","vt_layer","geometry","type","pointInPolygon","coordinates","_step","_iterator","_createForOfIteratorHelperLoose","done","value","getTileResult","results","muniCd","lv01Nm","gsiReverseGeocoder","_ref","lat","lon","response","_results$results","_results$results2","getElevation","elevation","parseFloat","longitude","latitude","latLonToAddress","Error","MuniRegex","getMuniMap","muniMapObj","split","line","test","muniRecord","muniRecordArray","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","searchAddress","q","BaseURL"],"mappings":"usCAQA,IAAMA,EAA2D,CAC/DC,GAAI,CACFC,SAAU,GAEVC,QAAS,yEACTC,MAAO,kBACPC,UAAW,SAAUC,GAAwB,IAAAC,EAAAC,EAS3C,MARsC,CACpCC,KACE,IAAMC,OAAOJ,EAAQK,IAAIC,OACrBF,OAAOJ,EAAQK,QACXD,OAAOJ,EAAQK,IACzBE,WAAYN,OAAFA,EAAED,EAAQQ,iBAARP,EAAAA,EAAoBM,WAChCE,KAAMP,OAAFA,EAAEF,EAAQQ,iBAARN,EAAAA,EAAoBO,KAG9B,IAKJf,EAAegB,QAAUhB,EAAeC,GChBxC,IAAMgB,EAAMC,EACVC,EAAMC,OAAO,CACXC,QAAS,MAEX,CACEC,IAAK,QAITL,EAAIM,aAAaC,QAAQC,IAAI,SAACC,GAAUC,IAAAA,EAAAC,EAChCC,EAAqB,OAAjBF,EAAGD,EAAOI,SAAOH,EAAI,GACzBI,EAAiBH,OAAbA,EAAGF,EAAOM,KAAGJ,EAAI,GACrBK,EAAQP,EAAOQ,OAAM,IACnB,IAAIC,gBAAgBT,EAAOQ,QAAkCE,WACjE,GAGJ,OADAC,QAAQC,IAAI,YADOT,GAAAA,EAAOE,EAAOE,GAE1BP,CACT,GAEA,IAAMa,EAAiBvC,EAAegB,QAShCwB,EAAmB,SACvBC,EACAC,GACqC,IACrC,IAAMC,EAAGC,EAAQL,GAAAA,EAAmBG,GACpCG,EAAeC,EAAeL,EAAQE,EAAIzC,UAAnC6C,EAACF,EAAA,GAAEG,EAACH,EAAyC,GAAA,OAAAI,QAAAC,QClCzC,SACXH,EACAC,EACAN,EACAzB,QAAqB,IAArBA,IAAAA,EAAqBE,GAAK,IACHgC,IAMnBC,EANmBD,EAAAA,SAAAE,GAgBvB,OADa,IAAIC,EAAWF,EAChB,EAfNjD,EAAUuC,EA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AqC,IACV,OAAA5E,QAAAC,QAC/B/B,EAAMsC,IADdqE,yDACuB,CACpCpE,aAAc,OACdxB,OAAQ,CACN2F,EAAAA,MAEFlE,cALIyC,GAQN,OADYA,EAASrC,IACV,EACb,CAAC,MAAAG,GAAA,OAAAjB,QAAAkB,OAAAD,EAAA,CAAA"}
|
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("global-mercator"),require("axios"),require("axios-cache-interceptor"),require("point-in-polygon"),require("mapbox-vector-tile")):"function"==typeof define&&define.amd?define(["exports","global-mercator","axios","axios-cache-interceptor","point-in-polygon","mapbox-vector-tile"],r):r((e||self).jsMsearchGsiJp={},e.globalMercator,e.axios,e.axiosCacheInterceptor,e.pointInPolygon,e.mapboxVectorTile)}(this,function(e,r,t,o,n,a){function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=/*#__PURE__*/i(t),c=/*#__PURE__*/i(n);function l(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,o=Array(r);t<r;t++)o[t]=e[t];return o}function u(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return l(e,r);var t={}.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?l(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function f(){return f=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)({}).hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},f.apply(null,arguments)}var p={JP:{zoomBase:10,tileUrl:"https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf",layer:"japanese-admins",getResult:function(e){var r,t;return{code:5===String(e.id).length?String(e.id):"0"+String(e.id),prefecture:null==(r=e.properties)?void 0:r.prefecture,city:null==(t=e.properties)?void 0:t.city}}}};p.DEFAULT=p.JP;var d=o.setupCache(s.default.create({timeout:2e3}),{ttl:864e5});d.interceptors.request.use(function(e){var r=
|
|
1
|
+
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("global-mercator"),require("axios"),require("axios-cache-interceptor"),require("point-in-polygon"),require("mapbox-vector-tile")):"function"==typeof define&&define.amd?define(["exports","global-mercator","axios","axios-cache-interceptor","point-in-polygon","mapbox-vector-tile"],r):r((e||self).jsMsearchGsiJp={},e.globalMercator,e.axios,e.axiosCacheInterceptor,e.pointInPolygon,e.mapboxVectorTile)}(this,function(e,r,t,o,n,a){function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=/*#__PURE__*/i(t),c=/*#__PURE__*/i(n);function l(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,o=Array(r);t<r;t++)o[t]=e[t];return o}function u(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return l(e,r);var t={}.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?l(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function f(){return f=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)({}).hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},f.apply(null,arguments)}var p={JP:{zoomBase:10,tileUrl:"https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf",layer:"japanese-admins",getResult:function(e){var r,t;return{code:5===String(e.id).length?String(e.id):"0"+String(e.id),prefecture:null==(r=e.properties)?void 0:r.prefecture,city:null==(t=e.properties)?void 0:t.city}}}};p.DEFAULT=p.JP;var d=o.setupCache(s.default.create({timeout:2e3}),{ttl:864e5});d.interceptors.request.use(function(e){var r,t,o=null!=(r=e.baseURL)?r:"",n=null!=(t=e.url)?t:"",a=e.params?"?"+new URLSearchParams(e.params).toString():"";return console.log("Full URL:",""+o+n+a),e});var g=p.DEFAULT,m=function(e,t){try{var o=f({},g,t),n=r.lngLatToGoogle(e,o.zoomBase),i=n[0],l=n[1];return Promise.resolve(function(e,r,t,o){void 0===o&&(o=s.default);try{var n,i=function(e){return new a.VectorTile(n)},c=t.tileUrl.replace("{z}",String(t.zoomBase)).replace("{x}",String(e)).replace("{y}",String(r)),l=function(e,r){try{var t=Promise.resolve(o.get(c,{responseType:"arraybuffer"})).then(function(e){n=Buffer.from(e.data,"binary")})}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(0,function(e){throw e});return Promise.resolve(l&&l.then?l.then(i):i())}catch(e){return Promise.reject(e)}}(i,l,o,d)).then(function(r){var t=function(e,r,t,o,n){var a=Object.keys(e.layers);Array.isArray(a)||(a=[a]);var i={};return a.forEach(function(s){var l=e.layers[s];if(l&&n.layer===l.name)for(var f=0;f<l.length;f++){var p=l.feature(f).toGeoJSON(r,t,n.zoomBase);if(a.length>1&&(p.properties.vt_layer=s),p.geometry&&"Polygon"===p.geometry.type)c.default(o,p.geometry.coordinates[0])&&(i=n.getResult(p));else if(p.geometry&&"MultiPolygon"===p.geometry.type)for(var d,g=u(p.geometry.coordinates);!(d=g()).done;)if(c.default(o,d.value[0])){i=n.getResult(p);break}}}),i}(r,i,l,e,o);return{results:{muniCd:t.code,lv01Nm:t.city},code:t.code,prefecture:t.prefecture,city:t.city}})}catch(e){return Promise.reject(e)}},y=function(e){var r=e.lat,t=e.lon;try{return Promise.resolve(d.get("https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress",{responseType:"json",params:{lat:r,lon:t}})).then(function(e){var r,t,o=e.data;return f({},o,{code:null==o||null==(r=o.results)?void 0:r.muniCd,city:null==o||null==(t=o.results)?void 0:t.lv01Nm})})}catch(e){return Promise.reject(e)}},v=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g;e.getCityMap=function(){try{return Promise.resolve(function(e,r){try{var t=Promise.resolve(s.default.get("https://maps.gsi.go.jp/js/muni.js",{responseType:"text",timeout:500})).then(function(e){return r={},e.data.split("\n").forEach(function(e){if(v.test(e)){var t=function(e){var r=e.replace(v,"$1"),t=r.split(",");if(4!==t.length)throw new Error("invalid muni record: "+r);var o=t[0],n=t[1],a=t[2],i=t[3];return a=a.padStart(5,"0"),{prefCode:o=o.padStart(2,"0"),prefName:n,cityCode:a,cityName:i}}(e);r[t.cityCode]=t}}),r;var r})}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(0,function(e){return console.log("Failed to get muni map: "+e),{}}))}catch(e){return Promise.reject(e)}},e.getElevation=function(e,r){try{return Promise.resolve(d.get("https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php",{responseType:"json",params:{lat:e,lon:r}})).then(function(t){var o=parseFloat(t.data.elevation);return{longitude:r,latitude:e,elevation:o}})}catch(e){return Promise.reject(e)}},e.gsiReverseGeocoder=y,e.latLonToAddress=function(e,r){try{return Promise.resolve(function(t,o){try{var n=Promise.resolve(m([r,e])).then(function(e){if(!e.code)throw new Error("Failed to get city code from open reverse geocoder");return e})}catch(e){return o(e)}return n&&n.then?n.then(void 0,o):n}(0,function(t){return console.log(t),console.log("Failed to get city code from open reverse geocoder. Try to get from GSI."),y({lat:e,lon:r})}))}catch(e){return Promise.reject(e)}},e.openReverseGeocoder=m,e.searchAddress=function(e){try{return Promise.resolve(s.default.get("https://msearch.gsi.go.jp/address-search/AddressSearch",{responseType:"json",params:{q:e}})).then(function(e){return e.data})}catch(e){return Promise.reject(e)}}});
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/countryOptions.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/muni.ts","../src/msearch.ts"],"sourcesContent":["import {\n ReverseGeocodingOptions,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\n\n/**\n * vector tiles settings for each country\n */\nconst countryOptions: { [s: string]: ReverseGeocodingOptions } = {\n JP: {\n zoomBase: 10,\n // tileUrl: `http://127.0.0.1:5500/docs/tiles/{z}/{x}/{y}.pbf`,\n tileUrl: 'https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf',\n layer: 'japanese-admins',\n getResult: function (feature: GeoJSON.Feature) {\n const res: ReverseGeocodingResultJP = {\n code:\n 5 === String(feature.id).length\n ? String(feature.id)\n : `0${String(feature.id)}`,\n prefecture: feature.properties?.prefecture,\n city: feature.properties?.city,\n };\n return res;\n },\n },\n};\n\n// default country options\ncountryOptions.DEFAULT = countryOptions.JP;\n\nexport default countryOptions;\n","import { lngLatToGoogle } from 'global-mercator';\nimport axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport {\n ReverseGeocodingOptions,\n ReverseGeocodingResult,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\nimport countryOptions from './countryOptions';\nimport { getTile, getTileResult } from './utils';\n\ntype LngLat = [number, number];\n\nconst api = setupCache(\n axios.create({\n timeout: 2000,\n }),\n {\n ttl: 60 * 60 * 24 * 1000, // 1 day\n }\n);\n\napi.interceptors.request.use((config) => {\n const fullUrl = `${config.baseURL}${config.url}?${new URLSearchParams(\n config.params\n ).toString()}`;\n console.log('Full URL:', fullUrl);\n return config;\n});\n\nconst defaultOptions = countryOptions.DEFAULT;\n\n/**\n * Performs reverse geocoding to obtain location information based on longitude and latitude.\n *\n * @param lnglat - The longitude and latitude coordinates.\n * @param options - Optional parameters for reverse geocoding.\n * @returns A promise that resolves to the reverse geocoding result.\n */\nconst openReverseGeocoder = async (\n lnglat: LngLat,\n options?: ReverseGeocodingOptions\n): Promise<ReverseGeocodingResultJP> => {\n const opt = { ...defaultOptions, ...options };\n const [x, y] = lngLatToGoogle(lnglat, opt.zoomBase);\n const tile = await getTile(x, y, opt, api);\n const result: any = getTileResult(tile, x, y, lnglat, opt);\n return {\n results: {\n muniCd: result.code,\n lv01Nm: result.city,\n },\n code: result.code,\n prefecture: result.prefecture,\n city: result.city,\n };\n};\n\n/**\n * Performs reverse geocoding using the GSI (Geospatial Information Authority of Japan) API.\n * Given latitude and longitude coordinates, it returns the corresponding municipality code and city name.\n *\n * @param {Object} params - The parameters for the reverse geocoding request.\n * @param {number} params.lat - The latitude coordinate.\n * @param {number} params.lon - The longitude coordinate.\n * @returns {Promise<ReverseGeocodingResultJP>} A promise that resolves to an object containing the municipality code and city name.\n *\n * @example\n * const result = await gsiReverseGeocoder({ lat: 35.6895, lon: 139.6917 });\n * console.log(result); // { code: '13101', city: 'Chiyoda-ku' }\n */\nconst gsiReverseGeocoder = async ({\n lat,\n lon,\n}: {\n lat: number;\n lon: number;\n}): Promise<ReverseGeocodingResultJP> => {\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n const results = response.data;\n return {\n ...results,\n code: results?.results?.muniCd,\n city: results?.results?.lv01Nm,\n };\n};\n\n/**\n * Retrieves the elevation for a given longitude and latitude using the GSI API.\n *\n * @param {Object} coordinates - The coordinates for which to get the elevation.\n * @param {number} coordinates.lon - The longitude of the location.\n * @param {number} coordinates.lat - The latitude of the location.\n * @returns {Promise<{ longitude: number, latitude: number, elevation: number }>}\n * A promise that resolves to an object containing the longitude, latitude, and elevation.\n */\nconst getElevation = async (\n lat: number,\n lon: number\n): Promise<{ longitude: number; latitude: number; elevation: number }> => {\n // first, get elevation from GSI\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n\n const elevation = parseFloat(response.data.elevation);\n return { longitude: lon, latitude: lat, elevation };\n};\n\n/**\n * Reverse geocodes the given longitude and latitude to obtain a city code.\n *\n * @param {Object} params - The parameters for reverse geocoding.\n * @param {number} params.lon - The longitude of the location.\n * @param {number} params.lat - The latitude of the location.\n *\n * @returns {Promise<ReverseGeocodingResult>} A promise that resolves to the reverse geocoding result.\n *\n * @throws Will attempt to use an alternative geocoding service if the primary service fails.\n */\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodingResult> => {\n // first, get city code from open reverse geocoder(local)\n try {\n const result = await openReverseGeocoder([lon, lat]);\n // nếu như không thể lấy được code từ open reverse geocoder, thì sẽ lấy từ GSI\n if (!result.code) {\n throw new Error('Failed to get city code from open reverse geocoder');\n }\n\n return result;\n } catch (error) {\n // if failed, get city code from GSI\n console.log('Failed to get city code from open reverse geocoder. Try to get from GSI.');\n return gsiReverseGeocoder({ lat, lon });\n }\n};\n\nexport {\n latLonToAddress,\n getElevation,\n gsiReverseGeocoder,\n openReverseGeocoder,\n};\n","import pointInPolygon from 'point-in-polygon';\nimport axios, { AxiosInstance } from 'axios';\nimport { VectorTile } from 'mapbox-vector-tile';\nimport { ReverseGeocodingOptions, ReverseGeocodingResult } from './interfaces/index';\n\n/**\n * Get a tile from targeted country's tilesets by using x and y tile index\n * @param x x tile index\n * @param y y tile index\n * @param options ReverseGeocodingOptions\n * @param api Axios object\n * @returns VectorTile object\n */\nexport const getTile = async (\n x: number,\n y: number,\n options: ReverseGeocodingOptions,\n api: AxiosInstance = axios\n): Promise<VectorTile> => {\n const tileUrl = options.tileUrl\n .replace('{z}', String(options.zoomBase))\n .replace('{x}', String(x))\n .replace('{y}', String(y));\n\n let buffer;\n\n try {\n const res = await api.get(tileUrl, { responseType: 'arraybuffer' });\n buffer = Buffer.from(res.data, 'binary');\n } catch (error) {\n throw error;\n }\n\n const tile = new VectorTile(buffer);\n return tile;\n};\n\n/**\n * Get a result of reverse geocoding\n * @param tile VectorTile object\n * @param x x tile index\n * @param y y tile index\n * @param lnglat number[] longitude, latitude\n * @param options ReverseGeocodingOptions\n * @returns an object of result of reverse gecoding\n */\nexport const getTileResult = (\n tile: VectorTile,\n x: number,\n y: number,\n lnglat: [number, number],\n options: ReverseGeocodingOptions\n): ReverseGeocodingResult => {\n let layers = Object.keys(tile.layers);\n\n if (!Array.isArray(layers)) layers = [layers];\n\n let geocodingResult: ReverseGeocodingResult = {};\n layers.forEach((layerID) => {\n const layer = tile.layers[layerID];\n if (layer && options.layer === layer.name) {\n for (let i = 0; i < layer.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const feature: any = layer.feature(i).toGeoJSON(x, y, options.zoomBase);\n if (layers.length > 1) feature.properties.vt_layer = layerID;\n\n // Check if point is inside polygon\n // feature.geometry.coordinates is the polygon coordinates\n if (feature.geometry && feature.geometry.type === 'Polygon') {\n const coordinates = feature.geometry.coordinates[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n }\n } else if (feature.geometry && feature.geometry.type === 'MultiPolygon') {\n // Handle MultiPolygon: check if point is in any polygon\n const polygons = feature.geometry.coordinates;\n for (const polygon of polygons) {\n const coordinates = polygon[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n break;\n }\n }\n }\n }\n }\n });\n return geocodingResult;\n};\n\n","// Muni file url\nconst MuniURL = 'https://maps.gsi.go.jp/js/muni.js';\nconst MuniRegex = /GSI\\.MUNI_ARRAY\\[\"\\d+\"\\]\\s*=\\s*'(.*?)';/g;\n\nimport axios from 'axios';\n\ninterface MuniRecord {\n prefCode: string;\n prefName: string;\n cityCode: string;\n cityName: string;\n}\n\ninterface MuniMap {\n [key: string]: MuniRecord;\n}\n\ninterface AddressResults {\n muniCd: string;\n lv01Nm: string;\n mesh_code?: string;\n notes?: string;\n}\n\n/**\n * parse muni.js\n * @param muniMap\n */\nconst parseMuniMap = (muniMap: string) => {\n const muniMapObj: MuniMap = {};\n const lines = muniMap.split('\\n');\n lines.forEach((line) => {\n if (MuniRegex.test(line)) {\n const muniRecord = parseMuniRecord(line);\n muniMapObj[muniRecord.cityCode] = muniRecord;\n }\n });\n return muniMapObj;\n};\n\n/**\n * parse muni record\n * @param line\n */\nconst parseMuniRecord = (line: string) => {\n const muniRecord = line.replace(MuniRegex, '$1');\n\n const muniRecordArray = muniRecord.split(',');\n\n // validate muni record\n if (muniRecordArray.length !== 4) {\n throw new Error(`invalid muni record: ${muniRecord}`);\n }\n\n let [prefCode, prefName, cityCode, cityName] = muniRecordArray;\n\n // if cityCode is not 5 digits, add 0 to the beginning\n cityCode = cityCode.padStart(5, '0');\n\n // if prefCode is not 2 digits, add 0 to the beginning\n prefCode = prefCode.padStart(2, '0');\n\n return {\n prefCode: prefCode,\n prefName: prefName,\n cityCode: cityCode,\n cityName: cityName,\n };\n};\n\n/**\n * Fetches the municipality map data from a specified URL.\n *\n * @returns {Promise<object>} A promise that resolves to the parsed municipality map data.\n *\n * @throws Will log an error message and return an empty object if the request fails.\n */\nconst getMuniMap = async () => {\n try {\n const response = await axios.get(MuniURL, {\n responseType: 'text',\n timeout: 500,\n });\n\n const muniMap = response.data;\n return parseMuniMap(muniMap);\n } catch (error) {\n console.log(`Failed to get muni map: ${error}`);\n return {};\n }\n};\n\n/**\n * converts muni code to address name.\n *\n * @param muniMap\n * @param muniCode\n */\nconst muniCodeToAddressName = (muniMap: MuniMap, muniCode: string) => {\n const muniRecord = muniMap[muniCode];\n if (!muniRecord) {\n throw new Error(`muni code ${muniCode} not found`);\n }\n\n const add = `${muniRecord.prefName}${muniRecord.cityName}`;\n return add.replace(/ /g, '');\n};\n\n/**\n * converts address result to address name.\n * @param muniMap\n * @param addressResults\n */\nconst addressResultsToAddressName = (\n muniMap: MuniMap,\n addressResults: AddressResults\n) => {\n const mc = addressResults.muniCd;\n const muniName = muniCodeToAddressName(muniMap, mc);\n const addrName = `${muniName}${addressResults.lv01Nm}`;\n return addrName;\n};\n\nconst getMuniMapLocations = async () => {\n const muniMap = await getMuniMap();\n // muniMap is a map of all cities and wards in Japan\n // key: city code, value: { prefCode, prefName, cityCode, cityName }\n // we need to convert this to a map of all locations in Japan\n // key: prefCode , value: { prefName, cities: { key: cityCode, value: { cityCode, cityName, wards: { key: wardCode, value: { wardCode, wardName } } } } }\n\n const muniMapLocations = {};\n Object.keys(muniMap).forEach((cityCode) => {\n const muniRecord = muniMap[cityCode];\n const { prefCode, prefName, cityName } = muniRecord;\n if (!muniMapLocations[prefCode]) {\n muniMapLocations[prefCode] = { prefName, cities: {} };\n }\n\n // if cityName contains ' ', it is a ward\n // otherwise, it is a city\n if (cityName.includes(' ')) {\n // ward name is after ' '\n const [name, wardName] = cityName.split(' ');\n // find city has the same name\n const city: any = Object.values(muniMap).find(\n (c: any) => c.cityName === name\n );\n if (!city) {\n console.log(`City ${name} not found in prefCode ${prefCode}`);\n } else {\n // add ward to city\n muniMapLocations[prefCode].cities[city.cityCode].wards[cityCode] = {\n prefCode,\n cityCode: cityCode,\n cityName: `${name}${wardName}`,\n bigCityFlag: '1',\n bigCityCode: city.cityCode,\n };\n }\n } else {\n muniMapLocations[prefCode].cities[cityCode] = {\n prefCode,\n cityCode,\n cityName,\n wards: {},\n };\n }\n });\n\n // assign bigCityFlag to each city\n Object.keys(muniMapLocations).forEach((prefCode) => {\n const pref = muniMapLocations[prefCode];\n Object.keys(pref.cities).forEach((cityCode) => {\n const city = pref.cities[cityCode];\n const isBigCity = Object.values(city.wards).length > 0;\n if (isBigCity) {\n city.bigCityFlag = '2';\n } else {\n // delete wards\n delete city.wards;\n // if city is tokyo then bigCityFlag is 3, otherwise 0\n if (city.prefCode === '13') {\n city.bigCityFlag = '3';\n } else {\n city.bigCityFlag = '0';\n }\n }\n });\n });\n\n return muniMapLocations;\n};\n\nexport { getMuniMap };\n","import axios from 'axios';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\n\ntype Geometry = {\n coordinates: number[];\n type: string;\n};\n\ntype Properties = {\n addressCode: string;\n title: string;\n dataSource: string;\n};\ninterface SearchResults {\n geometry: Geometry;\n type: string;\n properties: Properties;\n}\n\n/**\n * search address by query\n */\nconst searchAddress = async (q: string): Promise<SearchResults> => {\n const url = `${BaseURL}/address-search/AddressSearch`;\n const response = await axios.get(url, {\n responseType: 'json',\n params: {\n q,\n },\n });\n\n const res = response.data;\n return res;\n};\n\nexport { searchAddress };\n"],"names":["countryOptions","JP","zoomBase","tileUrl","layer","getResult","feature","_feature$properties","_feature$properties2","code","String","id","length","prefecture","properties","city","DEFAULT","api","setupCache","axios","create","timeout","ttl","interceptors","request","use","config","fullUrl","baseURL","url","URLSearchParams","params","toString","console","log","defaultOptions","openReverseGeocoder","lnglat","options","opt","_extends","_lngLatToGoogle","lngLatToGoogle","x","y","Promise","resolve","_temp2","buffer","_result","VectorTile","replace","_temp","get","responseType","then","res","Buffer","from","data","_catch","error","e","reject","getTile","tile","result","layers","Object","keys","Array","isArray","geocodingResult","forEach","layerID","name","i","toGeoJSON","vt_layer","geometry","type","pointInPolygon","coordinates","_step","_iterator","_createForOfIteratorHelperLoose","done","value","getTileResult","results","muniCd","lv01Nm","gsiReverseGeocoder","_ref","lat","lon","response","_results$results","_results$results2","MuniRegex","muniMapObj","split","line","test","muniRecord","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","elevation","parseFloat","longitude","latitude","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"file":"index.umd.js","sources":["../src/countryOptions.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/muni.ts","../src/msearch.ts"],"sourcesContent":["import {\n ReverseGeocodingOptions,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\n\n/**\n * vector tiles settings for each country\n */\nconst countryOptions: { [s: string]: ReverseGeocodingOptions } = {\n JP: {\n zoomBase: 10,\n // tileUrl: `http://127.0.0.1:5500/docs/tiles/{z}/{x}/{y}.pbf`,\n tileUrl: 'https://skglobal-jsc.github.io/js-msearch-gsi-jp/tiles/{z}/{x}/{y}.pbf',\n layer: 'japanese-admins',\n getResult: function (feature: GeoJSON.Feature) {\n const res: ReverseGeocodingResultJP = {\n code:\n 5 === String(feature.id).length\n ? String(feature.id)\n : `0${String(feature.id)}`,\n prefecture: feature.properties?.prefecture,\n city: feature.properties?.city,\n };\n return res;\n },\n },\n};\n\n// default country options\ncountryOptions.DEFAULT = countryOptions.JP;\n\nexport default countryOptions;\n","import { lngLatToGoogle } from 'global-mercator';\nimport axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport {\n ReverseGeocodingOptions,\n ReverseGeocodingResult,\n ReverseGeocodingResultJP,\n} from './interfaces/index';\nimport countryOptions from './countryOptions';\nimport { getTile, getTileResult } from './utils';\n\ntype LngLat = [number, number];\n\nconst api = setupCache(\n axios.create({\n timeout: 2000,\n }),\n {\n ttl: 60 * 60 * 24 * 1000, // 1 day\n }\n);\n\napi.interceptors.request.use((config) => {\n const base = config.baseURL ?? '';\n const path = config.url ?? '';\n const query = config.params\n ? `?${new URLSearchParams(config.params as Record<string, string>).toString()}`\n : '';\n const fullUrl = `${base}${path}${query}`;\n console.log('Full URL:', fullUrl);\n return config;\n});\n\nconst defaultOptions = countryOptions.DEFAULT;\n\n/**\n * Performs reverse geocoding to obtain location information based on longitude and latitude.\n *\n * @param lnglat - The longitude and latitude coordinates.\n * @param options - Optional parameters for reverse geocoding.\n * @returns A promise that resolves to the reverse geocoding result.\n */\nconst openReverseGeocoder = async (\n lnglat: LngLat,\n options?: ReverseGeocodingOptions\n): Promise<ReverseGeocodingResultJP> => {\n const opt = { ...defaultOptions, ...options };\n const [x, y] = lngLatToGoogle(lnglat, opt.zoomBase);\n const tile = await getTile(x, y, opt, api);\n const result: any = getTileResult(tile, x, y, lnglat, opt);\n return {\n results: {\n muniCd: result.code,\n lv01Nm: result.city,\n },\n code: result.code,\n prefecture: result.prefecture,\n city: result.city,\n };\n};\n\n/**\n * Performs reverse geocoding using the GSI (Geospatial Information Authority of Japan) API.\n * Given latitude and longitude coordinates, it returns the corresponding municipality code and city name.\n *\n * @param {Object} params - The parameters for the reverse geocoding request.\n * @param {number} params.lat - The latitude coordinate.\n * @param {number} params.lon - The longitude coordinate.\n * @returns {Promise<ReverseGeocodingResultJP>} A promise that resolves to an object containing the municipality code and city name.\n *\n * @example\n * const result = await gsiReverseGeocoder({ lat: 35.6895, lon: 139.6917 });\n * console.log(result); // { code: '13101', city: 'Chiyoda-ku' }\n */\nconst gsiReverseGeocoder = async ({\n lat,\n lon,\n}: {\n lat: number;\n lon: number;\n}): Promise<ReverseGeocodingResultJP> => {\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n const results = response.data;\n return {\n ...results,\n code: results?.results?.muniCd,\n city: results?.results?.lv01Nm,\n };\n};\n\n/**\n * Retrieves the elevation for a given longitude and latitude using the GSI API.\n *\n * @param {Object} coordinates - The coordinates for which to get the elevation.\n * @param {number} coordinates.lon - The longitude of the location.\n * @param {number} coordinates.lat - The latitude of the location.\n * @returns {Promise<{ longitude: number, latitude: number, elevation: number }>}\n * A promise that resolves to an object containing the longitude, latitude, and elevation.\n */\nconst getElevation = async (\n lat: number,\n lon: number\n): Promise<{ longitude: number; latitude: number; elevation: number }> => {\n // first, get elevation from GSI\n const response = await api.get(\n 'https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php',\n {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n }\n );\n\n const elevation = parseFloat(response.data.elevation);\n return { longitude: lon, latitude: lat, elevation };\n};\n\n/**\n * Reverse geocodes the given longitude and latitude to obtain a city code.\n *\n * @param {Object} params - The parameters for reverse geocoding.\n * @param {number} params.lon - The longitude of the location.\n * @param {number} params.lat - The latitude of the location.\n *\n * @returns {Promise<ReverseGeocodingResult>} A promise that resolves to the reverse geocoding result.\n *\n * @throws Will attempt to use an alternative geocoding service if the primary service fails.\n */\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodingResult> => {\n // first, get city code from open reverse geocoder(local)\n try {\n const result = await openReverseGeocoder([lon, lat]);\n // nếu như không thể lấy được code từ open reverse geocoder, thì sẽ lấy từ GSI\n if (!result.code) {\n throw new Error('Failed to get city code from open reverse geocoder');\n }\n\n return result;\n } catch (error) {\n // if failed, get city code from GSI\n console.log(error);\n console.log('Failed to get city code from open reverse geocoder. Try to get from GSI.');\n return gsiReverseGeocoder({ lat, lon });\n }\n};\n\nexport {\n latLonToAddress,\n getElevation,\n gsiReverseGeocoder,\n openReverseGeocoder,\n};\n","import pointInPolygon from 'point-in-polygon';\nimport axios, { AxiosInstance } from 'axios';\nimport { VectorTile } from 'mapbox-vector-tile';\nimport { ReverseGeocodingOptions, ReverseGeocodingResult } from './interfaces/index';\n\n/**\n * Get a tile from targeted country's tilesets by using x and y tile index\n * @param x x tile index\n * @param y y tile index\n * @param options ReverseGeocodingOptions\n * @param api Axios object\n * @returns VectorTile object\n */\nexport const getTile = async (\n x: number,\n y: number,\n options: ReverseGeocodingOptions,\n api: AxiosInstance = axios\n): Promise<VectorTile> => {\n const tileUrl = options.tileUrl\n .replace('{z}', String(options.zoomBase))\n .replace('{x}', String(x))\n .replace('{y}', String(y));\n\n let buffer;\n\n try {\n const res = await api.get(tileUrl, { responseType: 'arraybuffer' });\n buffer = Buffer.from(res.data, 'binary');\n } catch (error) {\n throw error;\n }\n\n const tile = new VectorTile(buffer);\n return tile;\n};\n\n/**\n * Get a result of reverse geocoding\n * @param tile VectorTile object\n * @param x x tile index\n * @param y y tile index\n * @param lnglat number[] longitude, latitude\n * @param options ReverseGeocodingOptions\n * @returns an object of result of reverse gecoding\n */\nexport const getTileResult = (\n tile: VectorTile,\n x: number,\n y: number,\n lnglat: [number, number],\n options: ReverseGeocodingOptions\n): ReverseGeocodingResult => {\n let layers = Object.keys(tile.layers);\n\n if (!Array.isArray(layers)) layers = [layers];\n\n let geocodingResult: ReverseGeocodingResult = {};\n layers.forEach((layerID) => {\n const layer = tile.layers[layerID];\n if (layer && options.layer === layer.name) {\n for (let i = 0; i < layer.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const feature: any = layer.feature(i).toGeoJSON(x, y, options.zoomBase);\n if (layers.length > 1) feature.properties.vt_layer = layerID;\n\n // Check if point is inside polygon\n // feature.geometry.coordinates is the polygon coordinates\n if (feature.geometry && feature.geometry.type === 'Polygon') {\n const coordinates = feature.geometry.coordinates[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n }\n } else if (feature.geometry && feature.geometry.type === 'MultiPolygon') {\n // Handle MultiPolygon: check if point is in any polygon\n const polygons = feature.geometry.coordinates;\n for (const polygon of polygons) {\n const coordinates = polygon[0]; // First ring (exterior)\n const res = pointInPolygon(lnglat, coordinates);\n if (res) {\n geocodingResult = options.getResult(feature);\n break;\n }\n }\n }\n }\n }\n });\n return geocodingResult;\n};\n\n","// Muni file url\nconst MuniURL = 'https://maps.gsi.go.jp/js/muni.js';\nconst MuniRegex = /GSI\\.MUNI_ARRAY\\[\"\\d+\"\\]\\s*=\\s*'(.*?)';/g;\n\nimport axios from 'axios';\n\ninterface MuniRecord {\n prefCode: string;\n prefName: string;\n cityCode: string;\n cityName: string;\n}\n\ninterface MuniMap {\n [key: string]: MuniRecord;\n}\n\ninterface AddressResults {\n muniCd: string;\n lv01Nm: string;\n mesh_code?: string;\n notes?: string;\n}\n\n/**\n * parse muni.js\n * @param muniMap\n */\nconst parseMuniMap = (muniMap: string) => {\n const muniMapObj: MuniMap = {};\n const lines = muniMap.split('\\n');\n lines.forEach((line) => {\n if (MuniRegex.test(line)) {\n const muniRecord = parseMuniRecord(line);\n muniMapObj[muniRecord.cityCode] = muniRecord;\n }\n });\n return muniMapObj;\n};\n\n/**\n * parse muni record\n * @param line\n */\nconst parseMuniRecord = (line: string) => {\n const muniRecord = line.replace(MuniRegex, '$1');\n\n const muniRecordArray = muniRecord.split(',');\n\n // validate muni record\n if (muniRecordArray.length !== 4) {\n throw new Error(`invalid muni record: ${muniRecord}`);\n }\n\n let [prefCode, prefName, cityCode, cityName] = muniRecordArray;\n\n // if cityCode is not 5 digits, add 0 to the beginning\n cityCode = cityCode.padStart(5, '0');\n\n // if prefCode is not 2 digits, add 0 to the beginning\n prefCode = prefCode.padStart(2, '0');\n\n return {\n prefCode: prefCode,\n prefName: prefName,\n cityCode: cityCode,\n cityName: cityName,\n };\n};\n\n/**\n * Fetches the municipality map data from a specified URL.\n *\n * @returns {Promise<object>} A promise that resolves to the parsed municipality map data.\n *\n * @throws Will log an error message and return an empty object if the request fails.\n */\nconst getMuniMap = async () => {\n try {\n const response = await axios.get(MuniURL, {\n responseType: 'text',\n timeout: 500,\n });\n\n const muniMap = response.data;\n return parseMuniMap(muniMap);\n } catch (error) {\n console.log(`Failed to get muni map: ${error}`);\n return {};\n }\n};\n\n/**\n * converts muni code to address name.\n *\n * @param muniMap\n * @param muniCode\n */\nconst muniCodeToAddressName = (muniMap: MuniMap, muniCode: string) => {\n const muniRecord = muniMap[muniCode];\n if (!muniRecord) {\n throw new Error(`muni code ${muniCode} not found`);\n }\n\n const add = `${muniRecord.prefName}${muniRecord.cityName}`;\n return add.replace(/ /g, '');\n};\n\n/**\n * converts address result to address name.\n * @param muniMap\n * @param addressResults\n */\nconst addressResultsToAddressName = (\n muniMap: MuniMap,\n addressResults: AddressResults\n) => {\n const mc = addressResults.muniCd;\n const muniName = muniCodeToAddressName(muniMap, mc);\n const addrName = `${muniName}${addressResults.lv01Nm}`;\n return addrName;\n};\n\nconst getMuniMapLocations = async () => {\n const muniMap = await getMuniMap();\n // muniMap is a map of all cities and wards in Japan\n // key: city code, value: { prefCode, prefName, cityCode, cityName }\n // we need to convert this to a map of all locations in Japan\n // key: prefCode , value: { prefName, cities: { key: cityCode, value: { cityCode, cityName, wards: { key: wardCode, value: { wardCode, wardName } } } } }\n\n const muniMapLocations = {};\n Object.keys(muniMap).forEach((cityCode) => {\n const muniRecord = muniMap[cityCode];\n const { prefCode, prefName, cityName } = muniRecord;\n if (!muniMapLocations[prefCode]) {\n muniMapLocations[prefCode] = { prefName, cities: {} };\n }\n\n // if cityName contains ' ', it is a ward\n // otherwise, it is a city\n if (cityName.includes(' ')) {\n // ward name is after ' '\n const [name, wardName] = cityName.split(' ');\n // find city has the same name\n const city: any = Object.values(muniMap).find(\n (c: any) => c.cityName === name\n );\n if (!city) {\n console.log(`City ${name} not found in prefCode ${prefCode}`);\n } else {\n // add ward to city\n muniMapLocations[prefCode].cities[city.cityCode].wards[cityCode] = {\n prefCode,\n cityCode: cityCode,\n cityName: `${name}${wardName}`,\n bigCityFlag: '1',\n bigCityCode: city.cityCode,\n };\n }\n } else {\n muniMapLocations[prefCode].cities[cityCode] = {\n prefCode,\n cityCode,\n cityName,\n wards: {},\n };\n }\n });\n\n // assign bigCityFlag to each city\n Object.keys(muniMapLocations).forEach((prefCode) => {\n const pref = muniMapLocations[prefCode];\n Object.keys(pref.cities).forEach((cityCode) => {\n const city = pref.cities[cityCode];\n const isBigCity = Object.values(city.wards).length > 0;\n if (isBigCity) {\n city.bigCityFlag = '2';\n } else {\n // delete wards\n delete city.wards;\n // if city is tokyo then bigCityFlag is 3, otherwise 0\n if (city.prefCode === '13') {\n city.bigCityFlag = '3';\n } else {\n city.bigCityFlag = '0';\n }\n }\n });\n });\n\n return muniMapLocations;\n};\n\nexport { getMuniMap };\n","import axios from 'axios';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\n\ntype Geometry = {\n coordinates: number[];\n type: string;\n};\n\ntype Properties = {\n addressCode: string;\n title: string;\n dataSource: string;\n};\ninterface SearchResults {\n geometry: Geometry;\n type: string;\n properties: Properties;\n}\n\n/**\n * search address by query\n */\nconst searchAddress = async (q: string): Promise<SearchResults> => {\n const url = `${BaseURL}/address-search/AddressSearch`;\n const response = await axios.get(url, {\n responseType: 'json',\n params: {\n q,\n },\n });\n\n const res = response.data;\n return res;\n};\n\nexport { searchAddress };\n"],"names":["countryOptions","JP","zoomBase","tileUrl","layer","getResult","feature","_feature$properties","_feature$properties2","code","String","id","length","prefecture","properties","city","DEFAULT","api","setupCache","axios","create","timeout","ttl","interceptors","request","use","config","_config$baseURL","_config$url","base","baseURL","path","url","query","params","URLSearchParams","toString","console","log","defaultOptions","openReverseGeocoder","lnglat","options","opt","_extends","_lngLatToGoogle","lngLatToGoogle","x","y","Promise","resolve","_temp2","buffer","_result","VectorTile","replace","_temp","get","responseType","then","res","Buffer","from","data","_catch","error","e","reject","getTile","tile","result","layers","Object","keys","Array","isArray","geocodingResult","forEach","layerID","name","i","toGeoJSON","vt_layer","geometry","type","pointInPolygon","coordinates","_step","_iterator","_createForOfIteratorHelperLoose","done","value","getTileResult","results","muniCd","lv01Nm","gsiReverseGeocoder","_ref","lat","lon","response","_results$results","_results$results2","MuniRegex","muniMapObj","split","line","test","muniRecord","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","elevation","parseFloat","longitude","latitude","q","BaseURL"],"mappings":"4pDAQA,IAAMA,EAA2D,CAC/DC,GAAI,CACFC,SAAU,GAEVC,QAAS,yEACTC,MAAO,kBACPC,UAAW,SAAUC,GAAwB,IAAAC,EAAAC,EAS3C,MARsC,CACpCC,KACE,IAAMC,OAAOJ,EAAQK,IAAIC,OACrBF,OAAOJ,EAAQK,QACXD,OAAOJ,EAAQK,I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jp",
|
|
3
3
|
"description": "A client library for APIs that presented by Geospatial Information Authority of Japan",
|
|
4
|
-
"version": "2.1.
|
|
4
|
+
"version": "2.1.20",
|
|
5
5
|
"source": "src/index.ts",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"module": "dist/index.module.js",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
},
|
|
18
18
|
"scripts": {
|
|
19
19
|
"dev": "ts-node ./src/local.ts",
|
|
20
|
+
"test:latlon": "ts-node ./src/test_lat_lon_to_address.ts",
|
|
20
21
|
"create-data": "bash bin/download.sh && bash bin/build.sh",
|
|
21
22
|
"build": "microbundle --define PKG_VERSION=$npm_package_version && tsc -p tsconfig.interfaces.json",
|
|
22
23
|
"watch": "microbundle watch --define PKG_VERSION=$npm_package_version",
|