@sk-global/js-msearch-gsi-jp 1.1.22 → 1.1.23
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 +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=require("axios"),r=require("axios-cache-interceptor");function
|
|
1
|
+
var e=require("axios"),r=require("axios-cache-interceptor"),t=require("path");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/o(e),s=/*#__PURE__*/o(t),a=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g,i=r.setupCache(n.default.create({baseURL:"https://mreversegeocoder.gsi.go.jp",timeout:500}),{ttl:3e5}),c=function(e,r){try{var t=function(e,r){return{Ntokyo:e+10696e-8*e-17467e-9*r-.004602,Etokyo:r+46047e-9*e+83049e-9*r-.010041}}(e,r),o=function(e,r){var t=Math.floor(60*e/40),o=60*e%40,n=Math.floor(o/5),s=Math.floor(o%5*60/30),a=Math.floor(r-100),i=r-a-100,c=Math.floor(60*i/7.5),u=Math.floor(60*i%7.5*60/45);console.log(t,a,n,c,s,u);var d=""+t+a;return{meshCode:""+d+n+c+s+u,meshCode12:t,meshCode34:a,prefix:d}}(t.Ntokyo,t.Etokyo),n=o.meshCode,a=o.prefix;try{var i=s.default.join(__dirname,"data","mesh_data_"+a+".json"),c=require(i)[n];if(!c||0===c.length)return console.error("Mesh data not found for code "+n),Promise.resolve(null);var u=c[0];return Promise.resolve({results:{muniCd:null==u?void 0:u.city_code,lv01Nm:null==u?void 0:u.city_name,mesh_code:n,notes:null==u?void 0:u.notes}})}catch(e){return console.error("Error reading mesh data for prefix "+a+":",e),Promise.resolve(null)}}catch(e){return Promise.reject(e)}};exports.getMuniMap=function(){try{return Promise.resolve(function(e,r){try{var t=Promise.resolve(n.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(a.test(e)){var t=function(e){var r=e.replace(a,"$1"),t=r.split(",");if(4!==t.length)throw new Error("invalid muni record: "+r);var o=t[0],n=t[1],s=t[2],i=t[3];return s=s.padStart(5,"0"),{prefCode:o=o.padStart(2,"0"),prefName:n,cityCode:s,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.latLonToAddress=function(e,r){return Promise.resolve(c(e,r))},exports.reverseGeocodeByGsi=function(e,r){try{return Promise.resolve(i.get("reverse-geocoder/LonLatToAddress",{responseType:"json",params:{lat:e,lon:r}})).then(function(e){return e.data})}catch(e){return Promise.reject(e)}},exports.reverseGeocodeByLocal=c,exports.searchAddress=function(e){try{return Promise.resolve(n.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/muni.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/msearch.ts"],"sourcesContent":["// 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';\nimport { AddressResults, MuniMap } from './types';\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 * Get muni map (city or ward map by city code) from GSI\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 {\n getMuniMap,\n getMuniMapLocations,\n muniCodeToAddressName,\n addressResultsToAddressName,\n};\n","import axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\n\nimport { ReverseGeocodeResults } from './types';\nimport { getMuniMap } from './muni';\nimport { calculateMeshCode, convertToTokyoCoordinates } from './utils';\n\nconst api = setupCache(\n axios.create({\n baseURL: 'https://mreversegeocoder.gsi.go.jp',\n timeout: 500,\n })\n);\n/**\n * Reverse geocodes a given latitude and longitude using the mreversegeocoder API.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the reverse geocode results or null if no results are found.\n */\nconst reverseGeocodeByGsi = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // get address from mreversegeocoder API.\n const response = await api.get('reverse-geocoder/LonLatToAddress', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n return response.data;\n};\n\nconst reverseGeocodeByLocal = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // Convert lat and lon to Tokyo coordinates\n const { Etokyo, Ntokyo } = convertToTokyoCoordinates(lat, lon);\n\n // Get mesh code based on the Tokyo coordinates\n const { meshCode, meshCode12, meshCode34, prefix } = calculateMeshCode(\n Ntokyo,\n Etokyo\n );\n\n try {\n // Read the mesh data from the local file system using require\n const meshData = require(`./data/mesh_data_${prefix}.json`);\n\n // Get the data for the specific mesh code\n const meshArray = meshData[meshCode];\n if (!meshArray || meshArray.length === 0) {\n console.error(`Mesh data not found for code ${meshCode}`);\n return null\n }\n\n // return data same as GSI\n const [meshCodeData] = meshArray;\n return {\n results: {\n muniCd: meshCodeData?.city_code,\n lv01Nm: meshCodeData?.city_name,\n mesh_code: meshCode,\n notes: meshCodeData?.notes,\n },\n };\n } catch (error) {\n console.error(`Error reading mesh data for prefix ${prefix}:`, error);\n return null;\n }\n};\n\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // try to get address from gsi first\n // if there is an error, try to get address from local\n // try {\n // return await reverseGeocodeByGsi(lat, lon);\n // } catch (e) {\n // console.log('Error getting address from GSI:', e);\n // return await reverseGeocodeByLocal(lat, lon);\n // }\n\n return await reverseGeocodeByLocal(lat, lon);\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n};\n","/**\n * Converts geographical coordinates to Tokyo coordinates.\n *\n * This function adjusts the given latitude (N) and longitude (E) to the Tokyo coordinate system.\n *\n * @param lat - The latitude in degrees.\n * @param lon - The longitude in degrees.\n * @returns An object containing the converted Tokyo coordinates:\n * - `Ntokyo`: The converted latitude in Tokyo coordinate system.\n * - `Etokyo`: The converted longitude in Tokyo coordinate system.\n */\nexport function convertToTokyoCoordinates(\n lat: number,\n lon: number\n): { Ntokyo: number; Etokyo: number } {\n const Ntokyo = lat + 0.00010696 * lat - 0.000017467 * lon - 0.004602;\n const Etokyo = lon + 0.000046047 * lat + 0.000083049 * lon - 0.010041;\n return { Ntokyo, Etokyo };\n}\n\n/**\n * Calculates the mesh code based on the given Tokyo coordinates.\n * This function is refer from https://museum.bunmori.tokushima.jp/ogawa/map/meshtolatlon.html\n *\n * @param Ntokyo - The northern coordinate in Tokyo.\n * @param Etokyo - The eastern coordinate in Tokyo.\n * @returns The calculated mesh code as a string.\n */\nexport function calculateMeshCode(Ntokyo: number, Etokyo: number): {\n meshCode: string;\n meshCode12: number;\n meshCode34: number;\n prefix: string;\n} {\n const mesh12 = Math.floor((Ntokyo * 60) / 40);\n const mesh12a = (Ntokyo * 60) % 40;\n const mesh5 = Math.floor(mesh12a / 5);\n const mesh5a = mesh12a % 5;\n const mesh7 = Math.floor((mesh5a * 60) / 30);\n\n const mesh34 = Math.floor(Etokyo - 100);\n const mesh34a = Etokyo - mesh34 - 100;\n const mesh6 = Math.floor((mesh34a * 60) / 7.5);\n const mesh6a = (mesh34a * 60) % 7.5;\n const mesh8 = Math.floor((mesh6a * 60) / 45);\n\n console.log(mesh12, mesh34, mesh5, mesh6, mesh7, mesh8);\n const prefix = `${mesh12}${mesh34}`;\n const meshCode = `${prefix}${mesh5}${mesh6}${mesh7}${mesh8}`;\n return {\n meshCode: meshCode,\n meshCode12: mesh12,\n meshCode34: mesh34,\n prefix,\n }\n}\n","import axios from 'axios';\n\nimport { SearchResults } from './types';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\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":["MuniRegex","api","setupCache","axios","create","baseURL","timeout","reverseGeocodeByLocal","lat","lon","_convertToTokyoCoordi","Ntokyo","Etokyo","convertToTokyoCoordinates","_calculateMeshCode","mesh12","Math","floor","mesh12a","mesh5","mesh7","mesh34","mesh34a","mesh6","mesh8","console","log","prefix","meshCode","meshCode12","meshCode34","calculateMeshCode","meshArray","require","length","error","Promise","resolve","meshCodeData","results","muniCd","city_code","lv01Nm","city_name","mesh_code","notes","e","reject","get","responseType","then","response","muniMapObj","data","split","forEach","line","test","muniRecord","replace","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","_catch","params","q","BaseURL"],"mappings":"4JAEMA,EAAY,2CCKZC,EAAMC,EAAAA,WACVC,EAAAA,QAAMC,OAAO,CACXC,QAAS,qCACTC,QAAS,OA0BPC,WACJC,EACAC,GAAW,IAGX,IAAAC,EC9Bc,SACdF,EACAC,GAIA,MAAO,CAAEE,OAFMH,EAAM,SAAaA,EAAM,SAAcC,EAAM,QAE3CG,OADFH,EAAM,SAAcD,EAAM,SAAcC,EAAM,QAE/D,CDuB6BI,CAA0BL,EAAKC,GAG1DK,EChBc,SAAkBH,EAAgBC,GAMhD,IAAMG,EAASC,KAAKC,MAAgB,GAATN,EAAe,IACpCO,EAAoB,GAATP,EAAe,GAC1BQ,EAAQH,KAAKC,MAAMC,EAAU,GAE7BE,EAAQJ,KAAKC,MADJC,EAAU,EACU,GAAM,IAEnCG,EAASL,KAAKC,MAAML,EAAS,KAC7BU,EAAUV,EAASS,EAAS,IAC5BE,EAAQP,KAAKC,MAAiB,GAAVK,EAAgB,KAEpCE,EAAQR,KAAKC,MADO,GAAVK,EAAgB,IACG,GA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EAAtBI,GAAAA,EAAsBJ,EAAe,GAA3BK,EAAYL,KAQ/C,OALAI,EAAWA,EAASE,SAAS,EAAG,KAKzB,CACLJ,SAHFA,EAAWA,EAASI,SAAS,EAAG,KAI9BH,SAAUA,EACVC,SAAUA,EACVC,SAAUA,EAEd,CAnCyBE,CAAgBX,GACnCJ,EAAWM,EAAWM,UAAYN,CACnC,CACH,GACON,EATY,IACbA,CAoDyB,4DARHgB,CACxB,EAQH,SAAQjC,GAEP,OADAV,QAAQC,+BAA+BS,GAChC,CAAA,CACR,GACH,CAAC,MAAAW,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA,0BCOoB,SACnBtC,EACAC,GACyC2B,OAAAA,QAAAC,QAU5B9B,EAAsBC,EAAKC,GAC1C,8BAtEM,SACJD,EACAC,OACyC2B,OAAAA,QAAAC,QAElBpC,EAAI+C,IAAI,mCAAoC,CACjEC,aAAc,OACdoB,OAAQ,CACN7D,IAAAA,EACAC,IAAAA,MAEFyC,KANIC,SAAAA,GAQN,OAAOA,EAASE,IAAK,EACvB,CAAC,MAAAP,UAAAV,QAAAW,OAAAD,EAED,CAAA,wDE1BM,SAAuBwB,GAAqC,IACV,OAAAlC,QAAAC,QAC/BlC,EAAAA,QAAM6C,IADduB,yDACuB,CACpCtB,aAAc,OACdoB,OAAQ,CACNC,EAAAA,MAEFpB,cALIC,GAQN,OADYA,EAASE,IACV,EACb,CAAC,MAAAP,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/muni.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/msearch.ts"],"sourcesContent":["// 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';\nimport { AddressResults, MuniMap } from './types';\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 * Get muni map (city or ward map by city code) from GSI\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 {\n getMuniMap,\n getMuniMapLocations,\n muniCodeToAddressName,\n addressResultsToAddressName,\n};\n","import axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport path from 'path';\n\nimport { ReverseGeocodeResults } from './types';\nimport { getMuniMap } from './muni';\nimport { calculateMeshCode, convertToTokyoCoordinates } from './utils';\n\nconst api = setupCache(\n axios.create({\n baseURL: 'https://mreversegeocoder.gsi.go.jp',\n timeout: 500,\n }),\n {\n ttl: 1000 * 60 * 5 /* 5 minutes */,\n }\n);\n/**\n * Reverse geocodes a given latitude and longitude using the mreversegeocoder API.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the reverse geocode results or null if no results are found.\n */\nconst reverseGeocodeByGsi = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // get address from mreversegeocoder API.\n const response = await api.get('reverse-geocoder/LonLatToAddress', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n return response.data;\n};\n\nconst reverseGeocodeByLocal = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // Convert lat and lon to Tokyo coordinates\n const { Etokyo, Ntokyo } = convertToTokyoCoordinates(lat, lon);\n\n // Get mesh code based on the Tokyo coordinates\n const { meshCode, meshCode12, meshCode34, prefix } = calculateMeshCode(\n Ntokyo,\n Etokyo\n );\n\n try {\n // Read the mesh data from the local file system using require\n const meshDataPath = path.join(__dirname, 'data', `mesh_data_${prefix}.json`);\n const meshData = require(meshDataPath);\n\n // Get the data for the specific mesh code\n const meshArray = meshData[meshCode];\n if (!meshArray || meshArray.length === 0) {\n console.error(`Mesh data not found for code ${meshCode}`);\n return null\n }\n\n // return data same as GSI\n const [meshCodeData] = meshArray;\n return {\n results: {\n muniCd: meshCodeData?.city_code,\n lv01Nm: meshCodeData?.city_name,\n mesh_code: meshCode,\n notes: meshCodeData?.notes,\n },\n };\n } catch (error) {\n console.error(`Error reading mesh data for prefix ${prefix}:`, error);\n return null;\n }\n};\n\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // try to get address from gsi first\n // if there is an error, try to get address from local\n // try {\n // return await reverseGeocodeByGsi(lat, lon);\n // } catch (e) {\n // console.log('Error getting address from GSI:', e);\n // return await reverseGeocodeByLocal(lat, lon);\n // }\n\n return await reverseGeocodeByLocal(lat, lon);\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n};\n","/**\n * Converts geographical coordinates to Tokyo coordinates.\n *\n * This function adjusts the given latitude (N) and longitude (E) to the Tokyo coordinate system.\n *\n * @param lat - The latitude in degrees.\n * @param lon - The longitude in degrees.\n * @returns An object containing the converted Tokyo coordinates:\n * - `Ntokyo`: The converted latitude in Tokyo coordinate system.\n * - `Etokyo`: The converted longitude in Tokyo coordinate system.\n */\nexport function convertToTokyoCoordinates(\n lat: number,\n lon: number\n): { Ntokyo: number; Etokyo: number } {\n const Ntokyo = lat + 0.00010696 * lat - 0.000017467 * lon - 0.004602;\n const Etokyo = lon + 0.000046047 * lat + 0.000083049 * lon - 0.010041;\n return { Ntokyo, Etokyo };\n}\n\n/**\n * Calculates the mesh code based on the given Tokyo coordinates.\n * This function is refer from https://museum.bunmori.tokushima.jp/ogawa/map/meshtolatlon.html\n *\n * @param Ntokyo - The northern coordinate in Tokyo.\n * @param Etokyo - The eastern coordinate in Tokyo.\n * @returns The calculated mesh code as a string.\n */\nexport function calculateMeshCode(Ntokyo: number, Etokyo: number): {\n meshCode: string;\n meshCode12: number;\n meshCode34: number;\n prefix: string;\n} {\n const mesh12 = Math.floor((Ntokyo * 60) / 40);\n const mesh12a = (Ntokyo * 60) % 40;\n const mesh5 = Math.floor(mesh12a / 5);\n const mesh5a = mesh12a % 5;\n const mesh7 = Math.floor((mesh5a * 60) / 30);\n\n const mesh34 = Math.floor(Etokyo - 100);\n const mesh34a = Etokyo - mesh34 - 100;\n const mesh6 = Math.floor((mesh34a * 60) / 7.5);\n const mesh6a = (mesh34a * 60) % 7.5;\n const mesh8 = Math.floor((mesh6a * 60) / 45);\n\n console.log(mesh12, mesh34, mesh5, mesh6, mesh7, mesh8);\n const prefix = `${mesh12}${mesh34}`;\n const meshCode = `${prefix}${mesh5}${mesh6}${mesh7}${mesh8}`;\n return {\n meshCode: meshCode,\n meshCode12: mesh12,\n meshCode34: mesh34,\n prefix,\n }\n}\n","import axios from 'axios';\n\nimport { SearchResults } from './types';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\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":["MuniRegex","api","setupCache","axios","create","baseURL","timeout","ttl","reverseGeocodeByLocal","lat","lon","_convertToTokyoCoordi","Ntokyo","Etokyo","convertToTokyoCoordinates","_calculateMeshCode","mesh12","Math","floor","mesh12a","mesh5","mesh7","mesh34","mesh34a","mesh6","mesh8","console","log","prefix","meshCode","meshCode12","meshCode34","calculateMeshCode","meshDataPath","path","join","__dirname","meshArray","require","length","error","Promise","resolve","meshCodeData","results","muniCd","city_code","lv01Nm","city_name","mesh_code","notes","e","reject","get","responseType","then","response","muniMapObj","data","split","forEach","line","test","muniRecord","replace","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","_catch","params","q","BaseURL"],"mappings":"kMAEMA,EAAY,2CCMZC,EAAMC,EAAAA,WACVC,EAAK,QAACC,OAAO,CACXC,QAAS,qCACTC,QAAS,MAEX,CACEC,IAAK,MA0BHC,EAAqB,SACzBC,EACAC,OAGA,IAAAC,EClCc,SACdF,EACAC,GAIA,MAAO,CAAEE,OAFMH,EAAM,SAAaA,EAAM,SAAcC,EAAM,QAE3CG,OADFH,EAAM,SAAcD,EAAM,SAAcC,EAAM,QAE/D,CD2B6BI,CAA0BL,EAAKC,GAG1DK,ECpBc,SAAkBH,EAAgBC,GAMhD,IAAMG,EAASC,KAAKC,MAAgB,GAATN,EAAe,IACpCO,EAAoB,GAATP,EAAe,GAC1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2 @@
|
|
|
1
|
-
import e from"axios";import{setupCache as r}from"axios-cache-interceptor";var
|
|
1
|
+
import e from"axios";import{setupCache as r}from"axios-cache-interceptor";import o from"path";var t=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g,n=function(){try{return Promise.resolve(function(r,o){try{var n=Promise.resolve(e.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(t.test(e)){var o=function(e){var r=e.replace(t,"$1"),o=r.split(",");if(4!==o.length)throw new Error("invalid muni record: "+r);var n=o[0],s=o[1],a=o[2],i=o[3];return a=a.padStart(5,"0"),{prefCode:n=n.padStart(2,"0"),prefName:s,cityCode:a,cityName:i}}(e);r[o.cityCode]=o}}),r;var r})}catch(e){return o(e)}return n&&n.then?n.then(void 0,o):n}(0,function(e){return console.log("Failed to get muni map: "+e),{}}))}catch(e){return Promise.reject(e)}},s=r(e.create({baseURL:"https://mreversegeocoder.gsi.go.jp",timeout:500}),{ttl:3e5}),a=function(e,r){try{return Promise.resolve(s.get("reverse-geocoder/LonLatToAddress",{responseType:"json",params:{lat:e,lon:r}})).then(function(e){return e.data})}catch(e){return Promise.reject(e)}},i=function(e,r){try{var t=function(e,r){return{Ntokyo:e+10696e-8*e-17467e-9*r-.004602,Etokyo:r+46047e-9*e+83049e-9*r-.010041}}(e,r),n=function(e,r){var o=Math.floor(60*e/40),t=60*e%40,n=Math.floor(t/5),s=Math.floor(t%5*60/30),a=Math.floor(r-100),i=r-a-100,c=Math.floor(60*i/7.5),u=Math.floor(60*i%7.5*60/45);console.log(o,a,n,c,s,u);var l=""+o+a;return{meshCode:""+l+n+c+s+u,meshCode12:o,meshCode34:a,prefix:l}}(t.Ntokyo,t.Etokyo),s=n.meshCode,a=n.prefix;try{var i=o.join(__dirname,"data","mesh_data_"+a+".json"),c=require(i)[s];if(!c||0===c.length)return console.error("Mesh data not found for code "+s),Promise.resolve(null);var u=c[0];return Promise.resolve({results:{muniCd:null==u?void 0:u.city_code,lv01Nm:null==u?void 0:u.city_name,mesh_code:s,notes:null==u?void 0:u.notes}})}catch(e){return console.error("Error reading mesh data for prefix "+a+":",e),Promise.resolve(null)}}catch(e){return Promise.reject(e)}},c=function(e,r){return Promise.resolve(i(e,r))},u=function(r){try{return Promise.resolve(e.get("https://msearch.gsi.go.jp/address-search/AddressSearch",{responseType:"json",params:{q:r}})).then(function(e){return e.data})}catch(e){return Promise.reject(e)}};export{n as getMuniMap,c as latLonToAddress,a as reverseGeocodeByGsi,i as reverseGeocodeByLocal,u 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/muni.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/msearch.ts"],"sourcesContent":["// 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';\nimport { AddressResults, MuniMap } from './types';\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 * Get muni map (city or ward map by city code) from GSI\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 {\n getMuniMap,\n getMuniMapLocations,\n muniCodeToAddressName,\n addressResultsToAddressName,\n};\n","import axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\n\nimport { ReverseGeocodeResults } from './types';\nimport { getMuniMap } from './muni';\nimport { calculateMeshCode, convertToTokyoCoordinates } from './utils';\n\nconst api = setupCache(\n axios.create({\n baseURL: 'https://mreversegeocoder.gsi.go.jp',\n timeout: 500,\n })\n);\n/**\n * Reverse geocodes a given latitude and longitude using the mreversegeocoder API.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the reverse geocode results or null if no results are found.\n */\nconst reverseGeocodeByGsi = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // get address from mreversegeocoder API.\n const response = await api.get('reverse-geocoder/LonLatToAddress', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n return response.data;\n};\n\nconst reverseGeocodeByLocal = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // Convert lat and lon to Tokyo coordinates\n const { Etokyo, Ntokyo } = convertToTokyoCoordinates(lat, lon);\n\n // Get mesh code based on the Tokyo coordinates\n const { meshCode, meshCode12, meshCode34, prefix } = calculateMeshCode(\n Ntokyo,\n Etokyo\n );\n\n try {\n // Read the mesh data from the local file system using require\n const meshData = require(`./data/mesh_data_${prefix}.json`);\n\n // Get the data for the specific mesh code\n const meshArray = meshData[meshCode];\n if (!meshArray || meshArray.length === 0) {\n console.error(`Mesh data not found for code ${meshCode}`);\n return null\n }\n\n // return data same as GSI\n const [meshCodeData] = meshArray;\n return {\n results: {\n muniCd: meshCodeData?.city_code,\n lv01Nm: meshCodeData?.city_name,\n mesh_code: meshCode,\n notes: meshCodeData?.notes,\n },\n };\n } catch (error) {\n console.error(`Error reading mesh data for prefix ${prefix}:`, error);\n return null;\n }\n};\n\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // try to get address from gsi first\n // if there is an error, try to get address from local\n // try {\n // return await reverseGeocodeByGsi(lat, lon);\n // } catch (e) {\n // console.log('Error getting address from GSI:', e);\n // return await reverseGeocodeByLocal(lat, lon);\n // }\n\n return await reverseGeocodeByLocal(lat, lon);\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n};\n","/**\n * Converts geographical coordinates to Tokyo coordinates.\n *\n * This function adjusts the given latitude (N) and longitude (E) to the Tokyo coordinate system.\n *\n * @param lat - The latitude in degrees.\n * @param lon - The longitude in degrees.\n * @returns An object containing the converted Tokyo coordinates:\n * - `Ntokyo`: The converted latitude in Tokyo coordinate system.\n * - `Etokyo`: The converted longitude in Tokyo coordinate system.\n */\nexport function convertToTokyoCoordinates(\n lat: number,\n lon: number\n): { Ntokyo: number; Etokyo: number } {\n const Ntokyo = lat + 0.00010696 * lat - 0.000017467 * lon - 0.004602;\n const Etokyo = lon + 0.000046047 * lat + 0.000083049 * lon - 0.010041;\n return { Ntokyo, Etokyo };\n}\n\n/**\n * Calculates the mesh code based on the given Tokyo coordinates.\n * This function is refer from https://museum.bunmori.tokushima.jp/ogawa/map/meshtolatlon.html\n *\n * @param Ntokyo - The northern coordinate in Tokyo.\n * @param Etokyo - The eastern coordinate in Tokyo.\n * @returns The calculated mesh code as a string.\n */\nexport function calculateMeshCode(Ntokyo: number, Etokyo: number): {\n meshCode: string;\n meshCode12: number;\n meshCode34: number;\n prefix: string;\n} {\n const mesh12 = Math.floor((Ntokyo * 60) / 40);\n const mesh12a = (Ntokyo * 60) % 40;\n const mesh5 = Math.floor(mesh12a / 5);\n const mesh5a = mesh12a % 5;\n const mesh7 = Math.floor((mesh5a * 60) / 30);\n\n const mesh34 = Math.floor(Etokyo - 100);\n const mesh34a = Etokyo - mesh34 - 100;\n const mesh6 = Math.floor((mesh34a * 60) / 7.5);\n const mesh6a = (mesh34a * 60) % 7.5;\n const mesh8 = Math.floor((mesh6a * 60) / 45);\n\n console.log(mesh12, mesh34, mesh5, mesh6, mesh7, mesh8);\n const prefix = `${mesh12}${mesh34}`;\n const meshCode = `${prefix}${mesh5}${mesh6}${mesh7}${mesh8}`;\n return {\n meshCode: meshCode,\n meshCode12: mesh12,\n meshCode34: mesh34,\n prefix,\n }\n}\n","import axios from 'axios';\n\nimport { SearchResults } from './types';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\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":["MuniRegex","getMuniMap","Promise","resolve","axios","get","responseType","timeout","then","response","muniMapObj","data","split","forEach","line","test","muniRecord","replace","muniRecordArray","length","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","_catch","error","console","log","e","reject","api","setupCache","create","baseURL","reverseGeocodeByGsi","lat","lon","params","reverseGeocodeByLocal","_convertToTokyoCoordi","Ntokyo","Etokyo","convertToTokyoCoordinates","_calculateMeshCode","mesh12","Math","floor","mesh12a","mesh5","mesh7","mesh34","mesh34a","mesh6","mesh8","prefix","meshCode","meshCode12","meshCode34","calculateMeshCode","meshArray","require","meshCodeData","results","muniCd","city_code","lv01Nm","city_name","mesh_code","notes","latLonToAddress","searchAddress","q","BaseURL"],"mappings":"0EACA,IACMA,EAAY,2CAsDZC,EAAU,eAAcC,OAAAA,QAAAC,gCACxBD,QAAAC,QACqBC,EAAMC,IAzDjB,oCAyD8B,CACxCC,aAAc,OACdC,QAAS,OACTC,KAAA,SAHIC,GAMN,OApDIC,EAAsB,CAAE,EAmDZD,EAASE,KAlDLC,MAAM,MACtBC,QAAQ,SAACC,GACb,GAAId,EAAUe,KAAKD,GAAO,CACxB,IAAME,EAWY,SAACF,GACvB,IAAME,EAAaF,EAAKG,QAAQjB,EAAW,MAErCkB,EAAkBF,EAAWJ,MAAM,KAGzC,GAA+B,IAA3BM,EAAgBC,OAClB,MAAU,IAAAC,MAA8BJ,wBAAAA,GAG1C,IAAKK,EAA0CH,EAAe,GAA/CI,EAAgCJ,EAAtBK,GAAAA,EAAsBL,EAAe,GAA3BM,EAAYN,KAQ/C,OALAK,EAAWA,EAASE,SAAS,EAAG,KAKzB,CACLJ,SAHFA,EAAWA,EAASI,SAAS,EAAG,KAI9BH,SAAUA,EACVC,SAAUA,EACVC,SAAUA,EAEd,CAnCyBE,CAAgBZ,GACnCJ,EAAWM,EAAWO,UAAYP,CACnC,CACH,GACON,EATY,IACbA,CAoDyB,4DARHiB,CACxB,EAQH,SAAQC,GAEP,OADAC,QAAQC,+BAA+BF,GAChC,CAAA,CACR,GACH,CAAC,MAAAG,GAAA,OAAA7B,QAAA8B,OAAAD,EAAA,CAAA,EC9DKE,EAAMC,EACV9B,EAAM+B,OAAO,CACXC,QAAS,qCACT7B,QAAS,OAUP8B,EAAA,SACJC,EACAC,OACyCr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A5D,QAAAC,QAAO,CACL8D,QAAS,CACPC,aAAQF,SAAAA,EAAcG,UACtBC,OAAoB,MAAZJ,OAAY,EAAZA,EAAcK,UACtBC,UAAWZ,EACXa,MAAmB,MAAZP,OAAY,EAAZA,EAAcO,QAG1B,CAAC,MAAO3C,GAEP,OADAC,QAAQD,MAA4C6B,sCAAAA,MAAW7B,GAC/D1B,QAAAC,QAAO,KACR,CACH,CAAC,MAAA4B,GAAA,OAAA7B,QAAA8B,OAAAD,KAEKyC,EAAe,SACnBlC,EACAC,GACyCrC,OAAAA,QAAAC,QAU5BsC,EAAsBH,EAAKC,GAC1C,EEhFMkC,EAAA,SAAuBC,GAAqC,IACV,OAAAxE,QAAAC,QAC/BC,EAAMC,IADdsE,yDACuB,CACpCrE,aAAc,OACdkC,OAAQ,CACNkC,EAAAA,MAEFlE,cALIC,GAQN,OADYA,EAASE,IACV,EACb,CAAC,MAAAoB,GAAA,OAAA7B,QAAA8B,OAAAD,EAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.module.js","sources":["../src/muni.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/msearch.ts"],"sourcesContent":["// 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';\nimport { AddressResults, MuniMap } from './types';\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 * Get muni map (city or ward map by city code) from GSI\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 {\n getMuniMap,\n getMuniMapLocations,\n muniCodeToAddressName,\n addressResultsToAddressName,\n};\n","import axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport path from 'path';\n\nimport { ReverseGeocodeResults } from './types';\nimport { getMuniMap } from './muni';\nimport { calculateMeshCode, convertToTokyoCoordinates } from './utils';\n\nconst api = setupCache(\n axios.create({\n baseURL: 'https://mreversegeocoder.gsi.go.jp',\n timeout: 500,\n }),\n {\n ttl: 1000 * 60 * 5 /* 5 minutes */,\n }\n);\n/**\n * Reverse geocodes a given latitude and longitude using the mreversegeocoder API.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the reverse geocode results or null if no results are found.\n */\nconst reverseGeocodeByGsi = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // get address from mreversegeocoder API.\n const response = await api.get('reverse-geocoder/LonLatToAddress', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n return response.data;\n};\n\nconst reverseGeocodeByLocal = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // Convert lat and lon to Tokyo coordinates\n const { Etokyo, Ntokyo } = convertToTokyoCoordinates(lat, lon);\n\n // Get mesh code based on the Tokyo coordinates\n const { meshCode, meshCode12, meshCode34, prefix } = calculateMeshCode(\n Ntokyo,\n Etokyo\n );\n\n try {\n // Read the mesh data from the local file system using require\n const meshDataPath = path.join(__dirname, 'data', `mesh_data_${prefix}.json`);\n const meshData = require(meshDataPath);\n\n // Get the data for the specific mesh code\n const meshArray = meshData[meshCode];\n if (!meshArray || meshArray.length === 0) {\n console.error(`Mesh data not found for code ${meshCode}`);\n return null\n }\n\n // return data same as GSI\n const [meshCodeData] = meshArray;\n return {\n results: {\n muniCd: meshCodeData?.city_code,\n lv01Nm: meshCodeData?.city_name,\n mesh_code: meshCode,\n notes: meshCodeData?.notes,\n },\n };\n } catch (error) {\n console.error(`Error reading mesh data for prefix ${prefix}:`, error);\n return null;\n }\n};\n\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // try to get address from gsi first\n // if there is an error, try to get address from local\n // try {\n // return await reverseGeocodeByGsi(lat, lon);\n // } catch (e) {\n // console.log('Error getting address from GSI:', e);\n // return await reverseGeocodeByLocal(lat, lon);\n // }\n\n return await reverseGeocodeByLocal(lat, lon);\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n};\n","/**\n * Converts geographical coordinates to Tokyo coordinates.\n *\n * This function adjusts the given latitude (N) and longitude (E) to the Tokyo coordinate system.\n *\n * @param lat - The latitude in degrees.\n * @param lon - The longitude in degrees.\n * @returns An object containing the converted Tokyo coordinates:\n * - `Ntokyo`: The converted latitude in Tokyo coordinate system.\n * - `Etokyo`: The converted longitude in Tokyo coordinate system.\n */\nexport function convertToTokyoCoordinates(\n lat: number,\n lon: number\n): { Ntokyo: number; Etokyo: number } {\n const Ntokyo = lat + 0.00010696 * lat - 0.000017467 * lon - 0.004602;\n const Etokyo = lon + 0.000046047 * lat + 0.000083049 * lon - 0.010041;\n return { Ntokyo, Etokyo };\n}\n\n/**\n * Calculates the mesh code based on the given Tokyo coordinates.\n * This function is refer from https://museum.bunmori.tokushima.jp/ogawa/map/meshtolatlon.html\n *\n * @param Ntokyo - The northern coordinate in Tokyo.\n * @param Etokyo - The eastern coordinate in Tokyo.\n * @returns The calculated mesh code as a string.\n */\nexport function calculateMeshCode(Ntokyo: number, Etokyo: number): {\n meshCode: string;\n meshCode12: number;\n meshCode34: number;\n prefix: string;\n} {\n const mesh12 = Math.floor((Ntokyo * 60) / 40);\n const mesh12a = (Ntokyo * 60) % 40;\n const mesh5 = Math.floor(mesh12a / 5);\n const mesh5a = mesh12a % 5;\n const mesh7 = Math.floor((mesh5a * 60) / 30);\n\n const mesh34 = Math.floor(Etokyo - 100);\n const mesh34a = Etokyo - mesh34 - 100;\n const mesh6 = Math.floor((mesh34a * 60) / 7.5);\n const mesh6a = (mesh34a * 60) % 7.5;\n const mesh8 = Math.floor((mesh6a * 60) / 45);\n\n console.log(mesh12, mesh34, mesh5, mesh6, mesh7, mesh8);\n const prefix = `${mesh12}${mesh34}`;\n const meshCode = `${prefix}${mesh5}${mesh6}${mesh7}${mesh8}`;\n return {\n meshCode: meshCode,\n meshCode12: mesh12,\n meshCode34: mesh34,\n prefix,\n }\n}\n","import axios from 'axios';\n\nimport { SearchResults } from './types';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\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":["MuniRegex","getMuniMap","Promise","resolve","axios","get","responseType","timeout","then","response","muniMapObj","data","split","forEach","line","test","muniRecord","replace","muniRecordArray","length","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","_catch","error","console","log","e","reject","api","setupCache","create","baseURL","ttl","reverseGeocodeByGsi","lat","lon","params","reverseGeocodeByLocal","_convertToTokyoCoordi","Ntokyo","Etokyo","convertToTokyoCoordinates","_calculateMeshCode","mesh12","Math","floor","mesh12a","mesh5","mesh7","mesh34","mesh34a","mesh6","mesh8","prefix","meshCode","meshCode12","meshCode34","calculateMeshCode","meshDataPath","path","join","__dirname","meshArray","require","meshCodeData","results","muniCd","city_code","lv01Nm","city_name","mesh_code","notes","latLonToAddress","searchAddress","q","BaseURL"],"mappings":"8FACA,IACMA,EAAY,2CAsDZC,EAAU,eAAcC,OAAAA,QAAAC,gCACxBD,QAAAC,QACqBC,EAAMC,IAzDjB,oCAyD8B,CACxCC,aAAc,OACdC,QAAS,OACTC,KAAA,SAHIC,GAMN,OApDIC,EAAsB,CAAE,EAmDZD,EAASE,KAlDLC,MAAM,MACtBC,QAAQ,SAACC,GACb,GAAId,EAAUe,KAAKD,GAAO,CACxB,IAAME,EAWY,SAACF,GACvB,IAAME,EAAaF,EAAKG,QAAQjB,EAAW,MAErCkB,EAAkBF,EAAWJ,MAAM,KAGzC,GAA+B,IAA3BM,EAAgBC,OAClB,MAAU,IAAAC,MAA8BJ,wBAAAA,GAG1C,IAAKK,EAA0CH,EAAe,GAA/CI,EAAgCJ,EAAtBK,GAAAA,EAAsBL,EAAe,GAA3BM,EAAYN,KAQ/C,OALAK,EAAWA,EAASE,SAAS,EAAG,KAKzB,CACLJ,SAHFA,EAAWA,EAASI,SAAS,EAAG,KAI9BH,SAAUA,EACVC,SAAUA,EACVC,SAAUA,EAEd,CAnCyBE,CAAgBZ,GACnCJ,EAAWM,EA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OAAAA,EAEJ,CDPuDI,CAH/BnB,EAANC,OAAFD,EAANE,QAGAc,EAAQZ,EAARY,SAAkCD,EAAMX,EAANW,OAK1C,IAEE,IAAMK,EAAeC,EAAKC,KAAKC,UAAW,OAAqBR,aAAAA,WAIzDS,EAHWC,QAAQL,GAGEJ,GAC3B,IAAKQ,GAAkC,IAArBA,EAAUhD,OAE1B,OADAU,QAAQD,sCAAsC+B,GAC9CzD,QAAAC,QAAO,MAIT,IAAOkE,EAAgBF,KACvB,OAAAjE,QAAAC,QAAO,CACLmE,QAAS,CACPC,OAAQF,MAAAA,OAAAA,EAAAA,EAAcG,UACtBC,OAAQJ,MAAAA,OAAAA,EAAAA,EAAcK,UACtBC,UAAWhB,EACXiB,MAAmB,MAAZP,OAAY,EAAZA,EAAcO,QAG1B,CAAC,MAAOhD,GAEP,OADAC,QAAQD,4CAA4C8B,EAAM,IAAK9B,GAC/D1B,QAAAC,QAAO,KACR,CACH,CAAC,MAAA4B,UAAA7B,QAAA8B,OAAAD,KAEK8C,EAAA,SACJtC,EACAC,GACyCtC,OAAAA,QAAAC,QAU5BuC,EAAsBH,EAAKC,GAC1C,EErFMsC,EAAA,SAAuBC,GAAqC,IACV,OAAA7E,QAAAC,QAC/BC,EAAMC,IADd2E,yDACuB,CACpC1E,aAAc,OACdmC,OAAQ,CACNsC,EAAAA,MAEFvE,cALIC,GAQN,OADYA,EAASE,IACV,EACb,CAAC,MAAAoB,GAAA,OAAA7B,QAAA8B,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("axios"),require("axios-cache-interceptor")):"function"==typeof define&&define.amd?define(["exports","axios","axios-cache-interceptor"],r):r((e||self).jsMsearchGsiJp={},e.axios,e.axiosCacheInterceptor)}(this,function(e,r,o){function
|
|
1
|
+
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("axios"),require("axios-cache-interceptor"),require("path")):"function"==typeof define&&define.amd?define(["exports","axios","axios-cache-interceptor","path"],r):r((e||self).jsMsearchGsiJp={},e.axios,e.axiosCacheInterceptor,e.path)}(this,function(e,r,t,o){function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=/*#__PURE__*/n(r),a=/*#__PURE__*/n(o),i=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g,c=t.setupCache(s.default.create({baseURL:"https://mreversegeocoder.gsi.go.jp",timeout:500}),{ttl:3e5}),u=function(e,r){try{var t=function(e,r){return{Ntokyo:e+10696e-8*e-17467e-9*r-.004602,Etokyo:r+46047e-9*e+83049e-9*r-.010041}}(e,r),o=function(e,r){var t=Math.floor(60*e/40),o=60*e%40,n=Math.floor(o/5),s=Math.floor(o%5*60/30),a=Math.floor(r-100),i=r-a-100,c=Math.floor(60*i/7.5),u=Math.floor(60*i%7.5*60/45);console.log(t,a,n,c,s,u);var d=""+t+a;return{meshCode:""+d+n+c+s+u,meshCode12:t,meshCode34:a,prefix:d}}(t.Ntokyo,t.Etokyo),n=o.meshCode,s=o.prefix;try{var i=a.default.join(__dirname,"data","mesh_data_"+s+".json"),c=require(i)[n];if(!c||0===c.length)return console.error("Mesh data not found for code "+n),Promise.resolve(null);var u=c[0];return Promise.resolve({results:{muniCd:null==u?void 0:u.city_code,lv01Nm:null==u?void 0:u.city_name,mesh_code:n,notes:null==u?void 0:u.notes}})}catch(e){return console.error("Error reading mesh data for prefix "+s+":",e),Promise.resolve(null)}}catch(e){return Promise.reject(e)}};e.getMuniMap=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(i.test(e)){var t=function(e){var r=e.replace(i,"$1"),t=r.split(",");if(4!==t.length)throw new Error("invalid muni record: "+r);var o=t[0],n=t[1],s=t[2],a=t[3];return s=s.padStart(5,"0"),{prefCode:o=o.padStart(2,"0"),prefName:n,cityCode:s,cityName:a}}(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.latLonToAddress=function(e,r){return Promise.resolve(u(e,r))},e.reverseGeocodeByGsi=function(e,r){try{return Promise.resolve(c.get("reverse-geocoder/LonLatToAddress",{responseType:"json",params:{lat:e,lon:r}})).then(function(e){return e.data})}catch(e){return Promise.reject(e)}},e.reverseGeocodeByLocal=u,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/muni.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/msearch.ts"],"sourcesContent":["// 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';\nimport { AddressResults, MuniMap } from './types';\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 * Get muni map (city or ward map by city code) from GSI\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 {\n getMuniMap,\n getMuniMapLocations,\n muniCodeToAddressName,\n addressResultsToAddressName,\n};\n","import axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\n\nimport { ReverseGeocodeResults } from './types';\nimport { getMuniMap } from './muni';\nimport { calculateMeshCode, convertToTokyoCoordinates } from './utils';\n\nconst api = setupCache(\n axios.create({\n baseURL: 'https://mreversegeocoder.gsi.go.jp',\n timeout: 500,\n })\n);\n/**\n * Reverse geocodes a given latitude and longitude using the mreversegeocoder API.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the reverse geocode results or null if no results are found.\n */\nconst reverseGeocodeByGsi = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // get address from mreversegeocoder API.\n const response = await api.get('reverse-geocoder/LonLatToAddress', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n return response.data;\n};\n\nconst reverseGeocodeByLocal = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // Convert lat and lon to Tokyo coordinates\n const { Etokyo, Ntokyo } = convertToTokyoCoordinates(lat, lon);\n\n // Get mesh code based on the Tokyo coordinates\n const { meshCode, meshCode12, meshCode34, prefix } = calculateMeshCode(\n Ntokyo,\n Etokyo\n );\n\n try {\n // Read the mesh data from the local file system using require\n const meshData = require(`./data/mesh_data_${prefix}.json`);\n\n // Get the data for the specific mesh code\n const meshArray = meshData[meshCode];\n if (!meshArray || meshArray.length === 0) {\n console.error(`Mesh data not found for code ${meshCode}`);\n return null\n }\n\n // return data same as GSI\n const [meshCodeData] = meshArray;\n return {\n results: {\n muniCd: meshCodeData?.city_code,\n lv01Nm: meshCodeData?.city_name,\n mesh_code: meshCode,\n notes: meshCodeData?.notes,\n },\n };\n } catch (error) {\n console.error(`Error reading mesh data for prefix ${prefix}:`, error);\n return null;\n }\n};\n\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // try to get address from gsi first\n // if there is an error, try to get address from local\n // try {\n // return await reverseGeocodeByGsi(lat, lon);\n // } catch (e) {\n // console.log('Error getting address from GSI:', e);\n // return await reverseGeocodeByLocal(lat, lon);\n // }\n\n return await reverseGeocodeByLocal(lat, lon);\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n};\n","/**\n * Converts geographical coordinates to Tokyo coordinates.\n *\n * This function adjusts the given latitude (N) and longitude (E) to the Tokyo coordinate system.\n *\n * @param lat - The latitude in degrees.\n * @param lon - The longitude in degrees.\n * @returns An object containing the converted Tokyo coordinates:\n * - `Ntokyo`: The converted latitude in Tokyo coordinate system.\n * - `Etokyo`: The converted longitude in Tokyo coordinate system.\n */\nexport function convertToTokyoCoordinates(\n lat: number,\n lon: number\n): { Ntokyo: number; Etokyo: number } {\n const Ntokyo = lat + 0.00010696 * lat - 0.000017467 * lon - 0.004602;\n const Etokyo = lon + 0.000046047 * lat + 0.000083049 * lon - 0.010041;\n return { Ntokyo, Etokyo };\n}\n\n/**\n * Calculates the mesh code based on the given Tokyo coordinates.\n * This function is refer from https://museum.bunmori.tokushima.jp/ogawa/map/meshtolatlon.html\n *\n * @param Ntokyo - The northern coordinate in Tokyo.\n * @param Etokyo - The eastern coordinate in Tokyo.\n * @returns The calculated mesh code as a string.\n */\nexport function calculateMeshCode(Ntokyo: number, Etokyo: number): {\n meshCode: string;\n meshCode12: number;\n meshCode34: number;\n prefix: string;\n} {\n const mesh12 = Math.floor((Ntokyo * 60) / 40);\n const mesh12a = (Ntokyo * 60) % 40;\n const mesh5 = Math.floor(mesh12a / 5);\n const mesh5a = mesh12a % 5;\n const mesh7 = Math.floor((mesh5a * 60) / 30);\n\n const mesh34 = Math.floor(Etokyo - 100);\n const mesh34a = Etokyo - mesh34 - 100;\n const mesh6 = Math.floor((mesh34a * 60) / 7.5);\n const mesh6a = (mesh34a * 60) % 7.5;\n const mesh8 = Math.floor((mesh6a * 60) / 45);\n\n console.log(mesh12, mesh34, mesh5, mesh6, mesh7, mesh8);\n const prefix = `${mesh12}${mesh34}`;\n const meshCode = `${prefix}${mesh5}${mesh6}${mesh7}${mesh8}`;\n return {\n meshCode: meshCode,\n meshCode12: mesh12,\n meshCode34: mesh34,\n prefix,\n }\n}\n","import axios from 'axios';\n\nimport { SearchResults } from './types';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\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":["MuniRegex","api","setupCache","axios","create","baseURL","timeout","reverseGeocodeByLocal","lat","lon","_convertToTokyoCoordi","Ntokyo","Etokyo","convertToTokyoCoordinates","_calculateMeshCode","mesh12","Math","floor","mesh12a","mesh5","mesh7","mesh34","mesh34a","mesh6","mesh8","console","log","prefix","meshCode","meshCode12","meshCode34","calculateMeshCode","meshArray","require","length","error","Promise","resolve","meshCodeData","results","muniCd","city_code","lv01Nm","city_name","mesh_code","notes","e","reject","get","responseType","then","response","muniMapObj","data","split","forEach","line","test","muniRecord","replace","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","_catch","params","q","BaseURL"],"mappings":"kcAEMA,EAAY,2CCKZC,EAAMC,EAAAA,WACVC,EAAAA,QAAMC,OAAO,CACXC,QAAS,qCACTC,QAAS,OA0BPC,WACJC,EACAC,GAAW,IAGX,IAAAC,EC9Bc,SACdF,EACAC,GAIA,MAAO,CAAEE,OAFMH,EAAM,SAAaA,EAAM,SAAcC,EAAM,QAE3CG,OADFH,EAAM,SAAcD,EAAM,SAAcC,EAAM,QAE/D,CDuB6BI,CAA0BL,EAAKC,GAG1DK,EChBc,SAAkBH,EAAgBC,GAMhD,IAAMG,EAASC,KAAKC,MAAgB,GAATN,EAAe,IACpCO,EAAoB,GAATP,EAAe,GAC1BQ,EAAQH,KAAKC,MAAMC,EAAU,GAE7BE,EAAQJ,KAAKC,MADJC,EAAU,EACU,GAAM,IAEnCG,EAASL,KAAKC,MAAML,EAAS,KAC7BU,EAAUV,EAASS,EAAS,IAC5BE,EAAQP,KAAKC,MAAiB,GAAVK,EAAgB,KAEpCE,EAAQR,KAAKC,MADO,GAAVK,EAAgB,IACG,GAAM,IAEzCG,QAAQC,IAAIX,EAAQM,EAAQF,EAAOI,EAAOH,EAAOI,GACjD,IAAMG,EAAM,GAAMZ,EAASM,EAE3B,MAAO,CACLO,SAFkBD,GAAAA,EAASR,EAAQI,EAAQH,EAAQI,EAGnDK,WAAYd,EACZe,WAAYT,EACZM,OAAAA,EAEJ,CDXuDI,CAH/BrB,EAANC,OAAFD,EAANE,QAGAgB,E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,CAoDyB,4DARHgB,CACxB,EAQH,SAAQjC,GAEP,OADAV,QAAQC,+BAA+BS,GAChC,CAAA,CACR,GACH,CAAC,MAAAW,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA,oBCOoB,SACnBtC,EACAC,GACyC2B,OAAAA,QAAAC,QAU5B9B,EAAsBC,EAAKC,GAC1C,wBAtEM,SACJD,EACAC,OACyC2B,OAAAA,QAAAC,QAElBpC,EAAI+C,IAAI,mCAAoC,CACjEC,aAAc,OACdoB,OAAQ,CACN7D,IAAAA,EACAC,IAAAA,MAEFyC,KANIC,SAAAA,GAQN,OAAOA,EAASE,IAAK,EACvB,CAAC,MAAAP,UAAAV,QAAAW,OAAAD,EAED,CAAA,4CE1BM,SAAuBwB,GAAqC,IACV,OAAAlC,QAAAC,QAC/BlC,EAAAA,QAAM6C,IADduB,yDACuB,CACpCtB,aAAc,OACdoB,OAAQ,CACNC,EAAAA,MAEFpB,cALIC,GAQN,OADYA,EAASE,IACV,EACb,CAAC,MAAAP,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/muni.ts","../src/m_reverse_geocode.ts","../src/utils.ts","../src/msearch.ts"],"sourcesContent":["// 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';\nimport { AddressResults, MuniMap } from './types';\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 * Get muni map (city or ward map by city code) from GSI\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 {\n getMuniMap,\n getMuniMapLocations,\n muniCodeToAddressName,\n addressResultsToAddressName,\n};\n","import axios from 'axios';\nimport { setupCache } from 'axios-cache-interceptor';\nimport path from 'path';\n\nimport { ReverseGeocodeResults } from './types';\nimport { getMuniMap } from './muni';\nimport { calculateMeshCode, convertToTokyoCoordinates } from './utils';\n\nconst api = setupCache(\n axios.create({\n baseURL: 'https://mreversegeocoder.gsi.go.jp',\n timeout: 500,\n }),\n {\n ttl: 1000 * 60 * 5 /* 5 minutes */,\n }\n);\n/**\n * Reverse geocodes a given latitude and longitude using the mreversegeocoder API.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the reverse geocode results or null if no results are found.\n */\nconst reverseGeocodeByGsi = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // get address from mreversegeocoder API.\n const response = await api.get('reverse-geocoder/LonLatToAddress', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n return response.data;\n};\n\nconst reverseGeocodeByLocal = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // Convert lat and lon to Tokyo coordinates\n const { Etokyo, Ntokyo } = convertToTokyoCoordinates(lat, lon);\n\n // Get mesh code based on the Tokyo coordinates\n const { meshCode, meshCode12, meshCode34, prefix } = calculateMeshCode(\n Ntokyo,\n Etokyo\n );\n\n try {\n // Read the mesh data from the local file system using require\n const meshDataPath = path.join(__dirname, 'data', `mesh_data_${prefix}.json`);\n const meshData = require(meshDataPath);\n\n // Get the data for the specific mesh code\n const meshArray = meshData[meshCode];\n if (!meshArray || meshArray.length === 0) {\n console.error(`Mesh data not found for code ${meshCode}`);\n return null\n }\n\n // return data same as GSI\n const [meshCodeData] = meshArray;\n return {\n results: {\n muniCd: meshCodeData?.city_code,\n lv01Nm: meshCodeData?.city_name,\n mesh_code: meshCode,\n notes: meshCodeData?.notes,\n },\n };\n } catch (error) {\n console.error(`Error reading mesh data for prefix ${prefix}:`, error);\n return null;\n }\n};\n\nconst latLonToAddress = async (\n lat: number,\n lon: number\n): Promise<ReverseGeocodeResults | null> => {\n // try to get address from gsi first\n // if there is an error, try to get address from local\n // try {\n // return await reverseGeocodeByGsi(lat, lon);\n // } catch (e) {\n // console.log('Error getting address from GSI:', e);\n // return await reverseGeocodeByLocal(lat, lon);\n // }\n\n return await reverseGeocodeByLocal(lat, lon);\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n};\n","/**\n * Converts geographical coordinates to Tokyo coordinates.\n *\n * This function adjusts the given latitude (N) and longitude (E) to the Tokyo coordinate system.\n *\n * @param lat - The latitude in degrees.\n * @param lon - The longitude in degrees.\n * @returns An object containing the converted Tokyo coordinates:\n * - `Ntokyo`: The converted latitude in Tokyo coordinate system.\n * - `Etokyo`: The converted longitude in Tokyo coordinate system.\n */\nexport function convertToTokyoCoordinates(\n lat: number,\n lon: number\n): { Ntokyo: number; Etokyo: number } {\n const Ntokyo = lat + 0.00010696 * lat - 0.000017467 * lon - 0.004602;\n const Etokyo = lon + 0.000046047 * lat + 0.000083049 * lon - 0.010041;\n return { Ntokyo, Etokyo };\n}\n\n/**\n * Calculates the mesh code based on the given Tokyo coordinates.\n * This function is refer from https://museum.bunmori.tokushima.jp/ogawa/map/meshtolatlon.html\n *\n * @param Ntokyo - The northern coordinate in Tokyo.\n * @param Etokyo - The eastern coordinate in Tokyo.\n * @returns The calculated mesh code as a string.\n */\nexport function calculateMeshCode(Ntokyo: number, Etokyo: number): {\n meshCode: string;\n meshCode12: number;\n meshCode34: number;\n prefix: string;\n} {\n const mesh12 = Math.floor((Ntokyo * 60) / 40);\n const mesh12a = (Ntokyo * 60) % 40;\n const mesh5 = Math.floor(mesh12a / 5);\n const mesh5a = mesh12a % 5;\n const mesh7 = Math.floor((mesh5a * 60) / 30);\n\n const mesh34 = Math.floor(Etokyo - 100);\n const mesh34a = Etokyo - mesh34 - 100;\n const mesh6 = Math.floor((mesh34a * 60) / 7.5);\n const mesh6a = (mesh34a * 60) % 7.5;\n const mesh8 = Math.floor((mesh6a * 60) / 45);\n\n console.log(mesh12, mesh34, mesh5, mesh6, mesh7, mesh8);\n const prefix = `${mesh12}${mesh34}`;\n const meshCode = `${prefix}${mesh5}${mesh6}${mesh7}${mesh8}`;\n return {\n meshCode: meshCode,\n meshCode12: mesh12,\n meshCode34: mesh34,\n prefix,\n }\n}\n","import axios from 'axios';\n\nimport { SearchResults } from './types';\n\n// base url for msearch api\nconst BaseURL = 'https://msearch.gsi.go.jp';\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":["MuniRegex","api","setupCache","axios","create","baseURL","timeout","ttl","reverseGeocodeByLocal","lat","lon","_convertToTokyoCoordi","Ntokyo","Etokyo","convertToTokyoCoordinates","_calculateMeshCode","mesh12","Math","floor","mesh12a","mesh5","mesh7","mesh34","mesh34a","mesh6","mesh8","console","log","prefix","meshCode","meshCode12","meshCode34","calculateMeshCode","meshDataPath","path","join","__dirname","meshArray","require","length","error","Promise","resolve","meshCodeData","results","muniCd","city_code","lv01Nm","city_name","mesh_code","notes","e","reject","get","responseType","then","response","muniMapObj","data","split","forEach","line","test","muniRecord","replace","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","_catch","params","q","BaseURL"],"mappings":"sfAEMA,EAAY,2CCMZC,EAAMC,EAAAA,WACVC,EAAK,QAACC,OAAO,CACXC,QAAS,qCACTC,QAAS,MAEX,CACEC,IAAK,MA0BHC,EAAqB,SACzBC,EACAC,OAGA,IAAAC,EClCc,SACdF,EACAC,GAIA,MAAO,CAAEE,OAFMH,EAAM,SAAaA,EAAM,SAAcC,EAAM,QAE3CG,OADFH,EAAM,SAAcD,EAAM,SAAcC,EAAM,QAE/D,CD2B6BI,CAA0BL,EAAKC,GAG1DK,ECpBc,SAAkBH,EAAgBC,GAMhD,IAAMG,EAASC,KAAKC,MAAgB,GAATN,EAAe,IACpCO,EAAoB,GAATP,EAAe,GAC1BQ,EAAQH,KAAKC,MAAMC,EAAU,GAE7BE,EAAQJ,KAAKC,MADJC,EAAU,EACU,GAAM,IAEnCG,EAASL,KAAKC,MAAML,EAAS,KAC7BU,EAAUV,EAASS,EAAS,IAC5BE,EAAQP,KAAKC,MAAiB,GAAVK,EAAgB,KAEpCE,EAAQR,KAAKC,MADO,GAAVK,EAAgB,IACG,GAAM,IAEzCG,QAAQ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Ae,GAA/CG,EAAgCH,EAAtBI,GAAAA,EAAsBJ,EAAe,GAA3BK,EAAYL,KAQ/C,OALAI,EAAWA,EAASE,SAAS,EAAG,KAKzB,CACLJ,SAHFA,EAAWA,EAASI,SAAS,EAAG,KAI9BH,SAAUA,EACVC,SAAUA,EACVC,SAAUA,EAEd,CAnCyBE,CAAgBX,GACnCJ,EAAWM,EAAWM,UAAYN,CACnC,CACH,GACON,EATY,IACbA,CAoDyB,4DARHgB,CACxB,EAQH,SAAQjC,GAEP,OADAd,QAAQC,+BAA+Ba,GAChC,CAAA,CACR,GACH,CAAC,MAAAW,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA,oBCYK,SACJ1C,EACAC,GACyC+B,OAAAA,QAAAC,QAU5BlC,EAAsBC,EAAKC,GAC1C,iCAtEED,EACAC,GAAW,WAC8B+B,QAAAC,QAElBzC,EAAIoD,IAAI,mCAAoC,CACjEC,aAAc,OACdoB,OAAQ,CACNjE,IAAAA,EACAC,IAAAA,MAEF6C,cANIC,GAQN,OAAOA,EAASE,IAAK,EACvB,CAAC,MAAAP,GAAAV,OAAAA,QAAAW,OAAAD,EAED,CAAA,4CE9BM,SAAuBwB,GAAqC,IACV,OAAAlC,QAAAC,QAC/BvC,EAAAA,QAAMkD,IADduB,yDACuB,CACpCtB,aAAc,OACdoB,OAAQ,CACNC,EAAAA,MAEFpB,cALIC,GAQN,OADYA,EAASE,IACV,EACb,CAAC,MAAAP,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sk-global/js-msearch-gsi-jp",
|
|
3
3
|
"description": "A client library for APIs that presented by Geospatial Information Authority of Japan",
|
|
4
|
-
"version": "1.1.
|
|
4
|
+
"version": "1.1.23",
|
|
5
5
|
"source": "src/index.ts",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"module": "dist/index.module.js",
|