@sk-global/js-msearch-gsi-jp 1.1.23 → 1.1.24
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.d.ts +2 -2
- 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/dist/m_reverse_geocode.d.ts +57 -1
- package/dist/utils.d.ts +5 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { getMuniMap, latLonToAddress, reverseGeocodeByLocal, reverseGeocodeByGsi } from './m_reverse_geocode';
|
|
1
|
+
import { getMuniMap, latLonToAddress, reverseGeocodeByLocal, reverseGeocodeByGsi, getElevationFromOpenAPI, getElevationFromGSI, getElevation } from './m_reverse_geocode';
|
|
2
2
|
import { searchAddress } from './msearch';
|
|
3
|
-
export { latLonToAddress, getMuniMap, searchAddress, reverseGeocodeByLocal, reverseGeocodeByGsi };
|
|
3
|
+
export { latLonToAddress, getMuniMap, searchAddress, reverseGeocodeByLocal, reverseGeocodeByGsi, getElevationFromOpenAPI, getElevationFromGSI, getElevation, };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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
|
|
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}}function n(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var o=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,o.get?o:{enumerable:!0,get:function(){return e[t]}})}}),r.default=e,r}var s=/*#__PURE__*/o(e),a=/*#__PURE__*/n(t);function i(){return i=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},i.apply(null,arguments)}var u=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g,c=r.setupCache(s.default.create({baseURL:"https://mreversegeocoder.gsi.go.jp",timeout:500}),{ttl:864e5}),l=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,u=Math.floor(60*i/7.5),c=Math.floor(60*i%7.5*60/45);console.log(t,a,n,u,s,c);var l=""+t+a;return{meshCode:""+l+n+u+s+c,meshCode12:t,meshCode34:a,prefix:l}}(t.Ntokyo,t.Etokyo),n=o.meshCode,s=o.prefix;try{var i=a.join(__dirname,"data","mesh_data_"+s+".json"),u=require(i)[n];if(!u||0===u.length)return console.error("Mesh data not found for code "+n),Promise.resolve(null);var c=u[0];return Promise.resolve({results:{muniCd:null==c?void 0:c.city_code,lv01Nm:null==c?void 0:c.city_name,mesh_code:n,notes:null==c?void 0:c.notes}})}catch(e){return console.error("Error reading mesh data for prefix "+s+":",e),Promise.resolve(null)}}catch(e){return Promise.reject(e)}},d=function(e,r){try{return Promise.resolve(s.default.get("https://api.open-elevation.com/api/v1/lookup",{responseType:"json",timeout:2e3,params:{locations:e+","+r}})).then(function(e){var r=e.data;if(!r.results||0===r.results.length)return null;var t=r.results[0];return i({},t,{elevation:parseFloat(t.elevation)})})}catch(e){return Promise.reject(e)}},f=function(e,r){try{return Promise.resolve(c.get("general/dem/scripts/getelevation.php",{responseType:"json",params:{lat:e,lon:r}})).then(function(t){return{elevation:parseFloat(t.data.elevation),longitude:r,latitude:e}})}catch(e){return Promise.reject(e)}};exports.getElevation=function(e,r){try{return Promise.resolve(function(t,o){try{var n=Promise.resolve(f(e,r))}catch(e){return o(e)}return n&&n.then?n.then(void 0,o):n}(0,function(t){return console.log("Error getting elevation from GSI:",t),Promise.resolve(d(e,r))}))}catch(e){return Promise.reject(e)}},exports.getElevationFromGSI=f,exports.getElevationFromOpenAPI=d,exports.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(u.test(e)){var t=function(e){var r=e.replace(u,"$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)}},exports.latLonToAddress=function(e,r){return Promise.resolve(l(e,r))},exports.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)}},exports.reverseGeocodeByLocal=l,exports.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.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';\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,IAA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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 * as 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 * 60 * 24, // 24 hours\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\n/**\n * Reverse geocodes a given latitude and longitude by converting them to Tokyo coordinates,\n * calculating the corresponding mesh code, and retrieving the mesh data from the local file system.\n *\n * @param lat - The latitude to reverse geocode.\n * @param lon - The longitude to reverse geocode.\n * @returns A promise that resolves to the reverse geocode results or null if the mesh data is not found.\n *\n * @example\n * ```typescript\n * const results = await reverseGeocodeByLocal(35.6895, 139.6917);\n * if (results) {\n * console.log(results);\n * } else {\n * console.log('No data found for the given coordinates.');\n * }\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(\n __dirname,\n 'data',\n `mesh_data_${prefix}.json`\n );\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\n/**\n * Converts latitude and longitude coordinates to an address.\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.\n *\n * @remarks\n * This function attempts to get the address from a local reverse geocoding service.\n * The commented-out code shows an alternative approach where it first tries to get the address\n * from a GSI (Geospatial Information) service and falls back to the local service in case of an error.\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\nconst getElevationFromOpenAPI = async (\n lat: number,\n lon: number\n): Promise<{\n elevation: number;\n longitude: number;\n latitude: number;\n} | null> => {\n // get elevation from OpenAPI\n // https://api.open-elevation.com/api/v1/lookup?locations=36.682158333460485,137.29295833375718\n const response = await axios.get(\n 'https://api.open-elevation.com/api/v1/lookup',\n {\n responseType: 'json',\n timeout: 2000,\n params: {\n locations: `${lat},${lon}`,\n },\n }\n );\n const data = response.data;\n if (!data.results || data.results.length === 0) {\n return null;\n }\n const [elevation] = data.results;\n return {\n ...elevation,\n elevation: parseFloat(elevation.elevation),\n };\n};\n\nconst getElevationFromGSI = async (\n lat: number,\n lon: number\n): Promise<{\n elevation: number;\n longitude: number;\n latitude: number;\n}> => {\n // get elevation from GSI API\n // https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php?lon=137.29295833375718&lat=36.682158333460485\n const response = await api.get('general/dem/scripts/getelevation.php', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n const elevation = parseFloat(response.data.elevation);\n return { elevation, longitude: lon, latitude: lat };\n};\n\n/**\n * Retrieves the elevation for a given latitude and longitude.\n *\n * This function first attempts to get the elevation data from the GSI (Geospatial Information Authority of Japan).\n * If there is an error during this process, it falls back to retrieving the elevation data from an OpenAPI.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the elevation data.\n * @throws Will log an error message if both GSI and OpenAPI requests fail.\n */\nconst getElevation = async (lat: number, lon: number) => {\n // try to get elevation from GSI first\n // if there is an error, try to get elevation from OpenAPI\n try {\n return await getElevationFromGSI(lat, lon);\n } catch (e) {\n console.log('Error getting elevation from GSI:', e);\n return await getElevationFromOpenAPI(lat, lon);\n }\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n getElevationFromOpenAPI,\n getElevationFromGSI,\n getElevation,\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 An object containing the mesh code and its components:\n * - `meshCode`: The full mesh code.\n * - `meshCode12`: The first two digits of the mesh code.\n * - `meshCode34`: The third and fourth digits of the mesh code.\n * - `prefix`: The first four digits of the mesh code.\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","getElevationFromOpenAPI","get","responseType","params","locations","then","response","data","elevation","_extends","parseFloat","getElevationFromGSI","longitude","latitude","_catch","muniMapObj","split","forEach","line","test","muniRecord","replace","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","q","BaseURL"],"mappings":"wqBACA,IACMA,EAAY,2CCMZC,EAAMC,aACVC,EAAAA,QAAMC,OAAO,CACXC,QAAS,qCACTC,QAAS,MAEX,CACEC,IAAK,QA4CHC,WACJC,EACAC,GACyC,IAEzC,IAAAC,ECpDc,SACdF,EACAC,GAIA,MAAO,CAAEE,OAFMH,EAAM,SAAaA,EAAM,SAAcC,EAAM,QAE3CG,OADFH,EAAM,SAAcD,EAAM,SAAcC,EAAM,QAE/D,CD6C6BI,CAA0BL,EAAKC,GAG1DK,EClCc,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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OADAd,QAAQC,+BAA+Ba,GAChC,CAAA,CACR,GACH,CAAC,MAAAW,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA,0BC8CoB,SACnB1C,EACAC,UACyC+B,QAAAC,QAU5BlC,EAAsBC,EAAKC,GAC1C,uCAxGED,EACAC,GAAW,WAC8B+B,QAAAC,QAElBzC,EAAIqD,IAAI,mCAAoC,CACjEC,aAAc,OACdC,OAAQ,CACN/C,IAAAA,EACAC,IAAAA,MAEFgD,KAAA,SANIC,GAQN,OAAOA,EAASC,IAAK,EACvB,CAAC,MAAAT,UAAAV,QAAAW,OAAAD,EAoBD,CAAA,wDEhDM,SAAuBgC,GAAqC,IACV,OAAA1C,QAAAC,QAC/BvC,EAAAA,QAAMmD,IADd8B,yDACuB,CACpC7B,aAAc,OACdC,OAAQ,CACN2B,EAAAA,MAEFzB,cALIC,GAQN,OADYA,EAASC,IACV,EACb,CAAC,MAAAT,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA"}
|
package/dist/index.module.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"axios";import{setupCache as r}from"axios-cache-interceptor";import
|
|
1
|
+
import e from"axios";import{setupCache as r}from"axios-cache-interceptor";import*as t from"path";function o(){return o=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},o.apply(null,arguments)}var n=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g,s=function(){try{return Promise.resolve(function(r,t){try{var o=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(n.test(e)){var t=function(e){var r=e.replace(n,"$1"),t=r.split(",");if(4!==t.length)throw new Error("invalid muni record: "+r);var o=t[0],s=t[1],a=t[2],i=t[3];return a=a.padStart(5,"0"),{prefCode:o=o.padStart(2,"0"),prefName:s,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)}},a=r(e.create({baseURL:"https://mreversegeocoder.gsi.go.jp",timeout:500}),{ttl:864e5}),i=function(e,r){try{return Promise.resolve(a.get("reverse-geocoder/LonLatToAddress",{responseType:"json",params:{lat:e,lon:r}})).then(function(e){return e.data})}catch(e){return Promise.reject(e)}},c=function(e,r){try{var o=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 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 l=""+t+a;return{meshCode:""+l+n+c+s+u,meshCode12:t,meshCode34:a,prefix:l}}(o.Ntokyo,o.Etokyo),s=n.meshCode,a=n.prefix;try{var i=t.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)}},u=function(e,r){return Promise.resolve(c(e,r))},l=function(r,t){try{return Promise.resolve(e.get("https://api.open-elevation.com/api/v1/lookup",{responseType:"json",timeout:2e3,params:{locations:r+","+t}})).then(function(e){var r=e.data;if(!r.results||0===r.results.length)return null;var t=r.results[0];return o({},t,{elevation:parseFloat(t.elevation)})})}catch(e){return Promise.reject(e)}},m=function(e,r){try{return Promise.resolve(a.get("general/dem/scripts/getelevation.php",{responseType:"json",params:{lat:e,lon:r}})).then(function(t){return{elevation:parseFloat(t.data.elevation),longitude:r,latitude:e}})}catch(e){return Promise.reject(e)}},p=function(e,r){try{return Promise.resolve(function(t,o){try{var n=Promise.resolve(m(e,r))}catch(e){return o(e)}return n&&n.then?n.then(void 0,o):n}(0,function(t){return console.log("Error getting elevation from GSI:",t),Promise.resolve(l(e,r))}))}catch(e){return Promise.reject(e)}},h=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{p as getElevation,m as getElevationFromGSI,l as getElevationFromOpenAPI,s as getMuniMap,u as latLonToAddress,i as reverseGeocodeByGsi,c as reverseGeocodeByLocal,h 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';\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,EAAWO,UAAYP,CACnC,CACH,GACON,EATY,IACbA,CAoDyB,4DARHiB,CACxB,EAQH,SAAQC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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"}
|
|
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 * as 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 * 60 * 24, // 24 hours\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\n/**\n * Reverse geocodes a given latitude and longitude by converting them to Tokyo coordinates,\n * calculating the corresponding mesh code, and retrieving the mesh data from the local file system.\n *\n * @param lat - The latitude to reverse geocode.\n * @param lon - The longitude to reverse geocode.\n * @returns A promise that resolves to the reverse geocode results or null if the mesh data is not found.\n *\n * @example\n * ```typescript\n * const results = await reverseGeocodeByLocal(35.6895, 139.6917);\n * if (results) {\n * console.log(results);\n * } else {\n * console.log('No data found for the given coordinates.');\n * }\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(\n __dirname,\n 'data',\n `mesh_data_${prefix}.json`\n );\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\n/**\n * Converts latitude and longitude coordinates to an address.\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.\n *\n * @remarks\n * This function attempts to get the address from a local reverse geocoding service.\n * The commented-out code shows an alternative approach where it first tries to get the address\n * from a GSI (Geospatial Information) service and falls back to the local service in case of an error.\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\nconst getElevationFromOpenAPI = async (\n lat: number,\n lon: number\n): Promise<{\n elevation: number;\n longitude: number;\n latitude: number;\n} | null> => {\n // get elevation from OpenAPI\n // https://api.open-elevation.com/api/v1/lookup?locations=36.682158333460485,137.29295833375718\n const response = await axios.get(\n 'https://api.open-elevation.com/api/v1/lookup',\n {\n responseType: 'json',\n timeout: 2000,\n params: {\n locations: `${lat},${lon}`,\n },\n }\n );\n const data = response.data;\n if (!data.results || data.results.length === 0) {\n return null;\n }\n const [elevation] = data.results;\n return {\n ...elevation,\n elevation: parseFloat(elevation.elevation),\n };\n};\n\nconst getElevationFromGSI = async (\n lat: number,\n lon: number\n): Promise<{\n elevation: number;\n longitude: number;\n latitude: number;\n}> => {\n // get elevation from GSI API\n // https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php?lon=137.29295833375718&lat=36.682158333460485\n const response = await api.get('general/dem/scripts/getelevation.php', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n const elevation = parseFloat(response.data.elevation);\n return { elevation, longitude: lon, latitude: lat };\n};\n\n/**\n * Retrieves the elevation for a given latitude and longitude.\n *\n * This function first attempts to get the elevation data from the GSI (Geospatial Information Authority of Japan).\n * If there is an error during this process, it falls back to retrieving the elevation data from an OpenAPI.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the elevation data.\n * @throws Will log an error message if both GSI and OpenAPI requests fail.\n */\nconst getElevation = async (lat: number, lon: number) => {\n // try to get elevation from GSI first\n // if there is an error, try to get elevation from OpenAPI\n try {\n return await getElevationFromGSI(lat, lon);\n } catch (e) {\n console.log('Error getting elevation from GSI:', e);\n return await getElevationFromOpenAPI(lat, lon);\n }\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n getElevationFromOpenAPI,\n getElevationFromGSI,\n getElevation,\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 An object containing the mesh code and its components:\n * - `meshCode`: The full mesh code.\n * - `meshCode12`: The first two digits of the mesh code.\n * - `meshCode34`: The third and fourth digits of the mesh code.\n * - `prefix`: The first four digits of the mesh code.\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","getElevationFromOpenAPI","locations","elevation","_extends","parseFloat","getElevationFromGSI","longitude","latitude","getElevation","searchAddress","q","BaseURL"],"mappings":"yTACA,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,EC7DKE,EAAMC,EACV9B,EAAM+B,OAAO,CACXC,QAAS,qCACT7B,QAAS,MAEX,CACE8B,IAAK,QAUHC,WACJC,EACAC,GAAW,WAC8BtC,QAAAC,QAElB8B,EAAI5B,IAAI,mCAAoC,CACjEC,aAAc,OACdmC,OAAQ,CACNF,IAAAA,EACAC,IAAAA,MAEFhC,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C,GAC3C,GACH,CAAC,MAAAT,GAAA7B,OAAAA,QAAA8B,OAAAD,EAED,CAAA,EEpMMwD,EAAA,SAAuBC,GAAqC,IACV,OAAAtF,QAAAC,QAC/BC,EAAMC,IADdoF,yDACuB,CACpCnF,aAAc,OACdmC,OAAQ,CACN+C,EAAAA,MAEFhF,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"),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),
|
|
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}}function a(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var o=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,o.get?o:{enumerable:!0,get:function(){return e[t]}})}}),r.default=e,r}var s=/*#__PURE__*/n(r),i=/*#__PURE__*/a(o);function u(){return u=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},u.apply(null,arguments)}var c=/GSI\.MUNI_ARRAY\["\d+"\]\s*=\s*'(.*?)';/g,l=t.setupCache(s.default.create({baseURL:"https://mreversegeocoder.gsi.go.jp",timeout:500}),{ttl:864e5}),f=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),a=Math.floor(o%5*60/30),s=Math.floor(r-100),i=r-s-100,u=Math.floor(60*i/7.5),c=Math.floor(60*i%7.5*60/45);console.log(t,s,n,u,a,c);var l=""+t+s;return{meshCode:""+l+n+u+a+c,meshCode12:t,meshCode34:s,prefix:l}}(t.Ntokyo,t.Etokyo),n=o.meshCode,a=o.prefix;try{var s=i.join(__dirname,"data","mesh_data_"+a+".json"),u=require(s)[n];if(!u||0===u.length)return console.error("Mesh data not found for code "+n),Promise.resolve(null);var c=u[0];return Promise.resolve({results:{muniCd:null==c?void 0:c.city_code,lv01Nm:null==c?void 0:c.city_name,mesh_code:n,notes:null==c?void 0:c.notes}})}catch(e){return console.error("Error reading mesh data for prefix "+a+":",e),Promise.resolve(null)}}catch(e){return Promise.reject(e)}},d=function(e,r){try{return Promise.resolve(s.default.get("https://api.open-elevation.com/api/v1/lookup",{responseType:"json",timeout:2e3,params:{locations:e+","+r}})).then(function(e){var r=e.data;if(!r.results||0===r.results.length)return null;var t=r.results[0];return u({},t,{elevation:parseFloat(t.elevation)})})}catch(e){return Promise.reject(e)}},p=function(e,r){try{return Promise.resolve(l.get("general/dem/scripts/getelevation.php",{responseType:"json",params:{lat:e,lon:r}})).then(function(t){return{elevation:parseFloat(t.data.elevation),longitude:r,latitude:e}})}catch(e){return Promise.reject(e)}};e.getElevation=function(e,r){try{return Promise.resolve(function(t,o){try{var n=Promise.resolve(p(e,r))}catch(e){return o(e)}return n&&n.then?n.then(void 0,o):n}(0,function(t){return console.log("Error getting elevation from GSI:",t),Promise.resolve(d(e,r))}))}catch(e){return Promise.reject(e)}},e.getElevationFromGSI=p,e.getElevationFromOpenAPI=d,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(c.test(e)){var t=function(e){var r=e.replace(c,"$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],s=t[3];return a=a.padStart(5,"0"),{prefCode:o=o.padStart(2,"0"),prefName:n,cityCode:a,cityName:s}}(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(f(e,r))},e.reverseGeocodeByGsi=function(e,r){try{return Promise.resolve(l.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=f,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';\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,KAAK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AaF,EAAKG,QAAQhE,EAAW,MAErCiE,EAAkBF,EAAWJ,MAAM,KAGzC,GAA+B,IAA3BM,EAAgB1B,OAClB,MAAU,IAAA2B,MAA8BH,wBAAAA,GAG1C,IAAKI,EAA0CF,EAAe,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"}
|
|
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 * as 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 * 60 * 24, // 24 hours\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\n/**\n * Reverse geocodes a given latitude and longitude by converting them to Tokyo coordinates,\n * calculating the corresponding mesh code, and retrieving the mesh data from the local file system.\n *\n * @param lat - The latitude to reverse geocode.\n * @param lon - The longitude to reverse geocode.\n * @returns A promise that resolves to the reverse geocode results or null if the mesh data is not found.\n *\n * @example\n * ```typescript\n * const results = await reverseGeocodeByLocal(35.6895, 139.6917);\n * if (results) {\n * console.log(results);\n * } else {\n * console.log('No data found for the given coordinates.');\n * }\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(\n __dirname,\n 'data',\n `mesh_data_${prefix}.json`\n );\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\n/**\n * Converts latitude and longitude coordinates to an address.\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.\n *\n * @remarks\n * This function attempts to get the address from a local reverse geocoding service.\n * The commented-out code shows an alternative approach where it first tries to get the address\n * from a GSI (Geospatial Information) service and falls back to the local service in case of an error.\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\nconst getElevationFromOpenAPI = async (\n lat: number,\n lon: number\n): Promise<{\n elevation: number;\n longitude: number;\n latitude: number;\n} | null> => {\n // get elevation from OpenAPI\n // https://api.open-elevation.com/api/v1/lookup?locations=36.682158333460485,137.29295833375718\n const response = await axios.get(\n 'https://api.open-elevation.com/api/v1/lookup',\n {\n responseType: 'json',\n timeout: 2000,\n params: {\n locations: `${lat},${lon}`,\n },\n }\n );\n const data = response.data;\n if (!data.results || data.results.length === 0) {\n return null;\n }\n const [elevation] = data.results;\n return {\n ...elevation,\n elevation: parseFloat(elevation.elevation),\n };\n};\n\nconst getElevationFromGSI = async (\n lat: number,\n lon: number\n): Promise<{\n elevation: number;\n longitude: number;\n latitude: number;\n}> => {\n // get elevation from GSI API\n // https://mreversegeocoder.gsi.go.jp/general/dem/scripts/getelevation.php?lon=137.29295833375718&lat=36.682158333460485\n const response = await api.get('general/dem/scripts/getelevation.php', {\n responseType: 'json',\n params: {\n lat,\n lon,\n },\n });\n\n const elevation = parseFloat(response.data.elevation);\n return { elevation, longitude: lon, latitude: lat };\n};\n\n/**\n * Retrieves the elevation for a given latitude and longitude.\n *\n * This function first attempts to get the elevation data from the GSI (Geospatial Information Authority of Japan).\n * If there is an error during this process, it falls back to retrieving the elevation data from an OpenAPI.\n *\n * @param lat - The latitude coordinate.\n * @param lon - The longitude coordinate.\n * @returns A promise that resolves to the elevation data.\n * @throws Will log an error message if both GSI and OpenAPI requests fail.\n */\nconst getElevation = async (lat: number, lon: number) => {\n // try to get elevation from GSI first\n // if there is an error, try to get elevation from OpenAPI\n try {\n return await getElevationFromGSI(lat, lon);\n } catch (e) {\n console.log('Error getting elevation from GSI:', e);\n return await getElevationFromOpenAPI(lat, lon);\n }\n};\n\nexport {\n getMuniMap,\n latLonToAddress,\n reverseGeocodeByLocal,\n reverseGeocodeByGsi,\n getElevationFromOpenAPI,\n getElevationFromGSI,\n getElevation,\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 An object containing the mesh code and its components:\n * - `meshCode`: The full mesh code.\n * - `meshCode12`: The first two digits of the mesh code.\n * - `meshCode34`: The third and fourth digits of the mesh code.\n * - `prefix`: The first four digits of the mesh code.\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","getElevationFromOpenAPI","get","responseType","params","locations","then","response","data","elevation","_extends","parseFloat","getElevationFromGSI","longitude","latitude","_catch","muniMapObj","split","forEach","line","test","muniRecord","replace","muniRecordArray","Error","prefCode","prefName","cityCode","cityName","padStart","parseMuniRecord","q","BaseURL"],"mappings":"49BACA,IACMA,EAAY,2CCMZC,EAAMC,aACVC,EAAAA,QAAMC,OAAO,CACXC,QAAS,qCACTC,QAAS,MAEX,CACEC,IAAK,QA4CHC,WACJC,EACAC,GACyC,IAEzC,IAAAC,ECpDc,SACdF,EACAC,GAIA,MAAO,CAAEE,OAFMH,EAAM,SAAaA,EAAM,SAAcC,EAAM,QAE3CG,OADFH,EAAM,SAAcD,EAAM,SAAcC,EAAM,QAE/D,CD6C6BI,CAA0BL,EAAKC,GAG1DK,EClCc,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,CDOuDI,CAH/BrB,EAANC,OAAFD,EAANE,QAGAg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GAC1C,iCAxGED,EACAC,GAAW,WAC8B+B,QAAAC,QAElBzC,EAAIqD,IAAI,mCAAoC,CACjEC,aAAc,OACdC,OAAQ,CACN/C,IAAAA,EACAC,IAAAA,MAEFgD,KAAA,SANIC,GAQN,OAAOA,EAASC,IAAK,EACvB,CAAC,MAAAT,UAAAV,QAAAW,OAAAD,EAoBD,CAAA,4CEhDM,SAAuBgC,GAAqC,IACV,OAAA1C,QAAAC,QAC/BvC,EAAAA,QAAMmD,IADd8B,yDACuB,CACpC7B,aAAc,OACdC,OAAQ,CACN2B,EAAAA,MAEFzB,cALIC,GAQN,OADYA,EAASC,IACV,EACb,CAAC,MAAAT,GAAA,OAAAV,QAAAW,OAAAD,EAAA,CAAA"}
|
|
@@ -8,6 +8,62 @@ import { getMuniMap } from './muni';
|
|
|
8
8
|
* @returns A promise that resolves to the reverse geocode results or null if no results are found.
|
|
9
9
|
*/
|
|
10
10
|
declare const reverseGeocodeByGsi: (lat: number, lon: number) => Promise<ReverseGeocodeResults | null>;
|
|
11
|
+
/**
|
|
12
|
+
* Reverse geocodes a given latitude and longitude by converting them to Tokyo coordinates,
|
|
13
|
+
* calculating the corresponding mesh code, and retrieving the mesh data from the local file system.
|
|
14
|
+
*
|
|
15
|
+
* @param lat - The latitude to reverse geocode.
|
|
16
|
+
* @param lon - The longitude to reverse geocode.
|
|
17
|
+
* @returns A promise that resolves to the reverse geocode results or null if the mesh data is not found.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```typescript
|
|
21
|
+
* const results = await reverseGeocodeByLocal(35.6895, 139.6917);
|
|
22
|
+
* if (results) {
|
|
23
|
+
* console.log(results);
|
|
24
|
+
* } else {
|
|
25
|
+
* console.log('No data found for the given coordinates.');
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
11
29
|
declare const reverseGeocodeByLocal: (lat: number, lon: number) => Promise<ReverseGeocodeResults | null>;
|
|
30
|
+
/**
|
|
31
|
+
* Converts latitude and longitude coordinates to an address.
|
|
32
|
+
*
|
|
33
|
+
* @param lat - The latitude coordinate.
|
|
34
|
+
* @param lon - The longitude coordinate.
|
|
35
|
+
* @returns A promise that resolves to the reverse geocode results or null.
|
|
36
|
+
*
|
|
37
|
+
* @remarks
|
|
38
|
+
* This function attempts to get the address from a local reverse geocoding service.
|
|
39
|
+
* The commented-out code shows an alternative approach where it first tries to get the address
|
|
40
|
+
* from a GSI (Geospatial Information) service and falls back to the local service in case of an error.
|
|
41
|
+
*/
|
|
12
42
|
declare const latLonToAddress: (lat: number, lon: number) => Promise<ReverseGeocodeResults | null>;
|
|
13
|
-
|
|
43
|
+
declare const getElevationFromOpenAPI: (lat: number, lon: number) => Promise<{
|
|
44
|
+
elevation: number;
|
|
45
|
+
longitude: number;
|
|
46
|
+
latitude: number;
|
|
47
|
+
} | null>;
|
|
48
|
+
declare const getElevationFromGSI: (lat: number, lon: number) => Promise<{
|
|
49
|
+
elevation: number;
|
|
50
|
+
longitude: number;
|
|
51
|
+
latitude: number;
|
|
52
|
+
}>;
|
|
53
|
+
/**
|
|
54
|
+
* Retrieves the elevation for a given latitude and longitude.
|
|
55
|
+
*
|
|
56
|
+
* This function first attempts to get the elevation data from the GSI (Geospatial Information Authority of Japan).
|
|
57
|
+
* If there is an error during this process, it falls back to retrieving the elevation data from an OpenAPI.
|
|
58
|
+
*
|
|
59
|
+
* @param lat - The latitude coordinate.
|
|
60
|
+
* @param lon - The longitude coordinate.
|
|
61
|
+
* @returns A promise that resolves to the elevation data.
|
|
62
|
+
* @throws Will log an error message if both GSI and OpenAPI requests fail.
|
|
63
|
+
*/
|
|
64
|
+
declare const getElevation: (lat: number, lon: number) => Promise<{
|
|
65
|
+
elevation: number;
|
|
66
|
+
longitude: number;
|
|
67
|
+
latitude: number;
|
|
68
|
+
} | null>;
|
|
69
|
+
export { getMuniMap, latLonToAddress, reverseGeocodeByLocal, reverseGeocodeByGsi, getElevationFromOpenAPI, getElevationFromGSI, getElevation, };
|
package/dist/utils.d.ts
CHANGED
|
@@ -19,7 +19,11 @@ export declare function convertToTokyoCoordinates(lat: number, lon: number): {
|
|
|
19
19
|
*
|
|
20
20
|
* @param Ntokyo - The northern coordinate in Tokyo.
|
|
21
21
|
* @param Etokyo - The eastern coordinate in Tokyo.
|
|
22
|
-
* @returns
|
|
22
|
+
* @returns An object containing the mesh code and its components:
|
|
23
|
+
* - `meshCode`: The full mesh code.
|
|
24
|
+
* - `meshCode12`: The first two digits of the mesh code.
|
|
25
|
+
* - `meshCode34`: The third and fourth digits of the mesh code.
|
|
26
|
+
* - `prefix`: The first four digits of the mesh code.
|
|
23
27
|
*/
|
|
24
28
|
export declare function calculateMeshCode(Ntokyo: number, Etokyo: number): {
|
|
25
29
|
meshCode: string;
|
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.24",
|
|
5
5
|
"source": "src/index.ts",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"module": "dist/index.module.js",
|