├── LICENSE ├── README.md ├── media ├── 0F9651FC-E5F9-43FD-A1A5-5FA6B1FF395D.gif ├── 3DFC39F6-962E-4255-9337-DBAD908AAAC6.jpeg ├── 94455C7B-176B-4DA3-8754-A4CDC5AB482A.png ├── B6B02EBA-BCE4-45BC-A7B1-15C5B5363CBF.png ├── BB6E2934-E843-4F2F-9668-3C4890FA22DD.png ├── C9BF6F28-93CC-4F8F-A848-58FD1CDB901B.png └── D43ECEA3-0EF5-494B-A668-9954258A37D5.gif └── widget.js /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Bring Larry to Life 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scriptable-widget-interest-map 2 | 3 | A widget built using the iOS app Scriptable. It displays nearby Wikipedia articles and allows you to either read them or get Google Maps directions to them. 4 | 5 |

6 | 7 |

8 | 9 | ## Quickstart 10 | 11 | 1. [Get an API key from Google.](https://developers.google.com/maps/documentation/javascript/get-api-key) 12 | 2. Make sure to [enable Billing](https://console.cloud.google.com/project/_/billing/enable) on the Google Cloud Project. [Learn more here](https://developers.google.com/maps/gmp-get-started). 13 | 3. [Enable Google Maps Static API for your API key](https://console.developers.google.com/apis/library/static-maps-backend.googleapis.com) 14 | 4. [Download the Scriptable App for iOS.](https://scriptable.app/) 15 | 5. [Copy and paste widget.js into a new script on the Scriptable app.](https://raw.githubusercontent.com/bring-larry-to-life/scriptable-widget-interest-map/main/widget.js) 16 | 6. [Edit the script params section of the script to use your API key:](https://github.com/bring-larry-to-life/scriptable-widget-interest-map/blob/c770af05d7299316b4dd38d7accdeb8d0f2aabf1/widget.js#L13-L16) 17 | ``` 18 | const scriptParams = { 19 | apiKey: 'XXX', <--- Put the API key here! 20 | forceWidgetView: false, 21 | writeLogsIfException: false, 22 | logPerformanceMetrics: false 23 | } 24 | ``` 25 | 7. Create a new Scriptable widget on your home screen and edit it to use the script you downloaded. 26 | 8. Enjoy! 27 | 28 | ## Other ways to load parameters 29 | 30 | Sometimes storing widget parameters in the script itself is too limiting. For reasons explained below the script will attempt to load parameters in this order: 31 | 32 | 1. Parameters passed in from the widget on the home screen. 33 | * This is great for displaying multiple of the same widget on your home screen. Think different locations, different sizes, etc. 34 | * This is also great for sharing the script file without risking sharing sensitive information (API key). 35 | 2. JSON file "./storage/scriptname.json". 36 | * This is great when you are using tools that update the script's file regularly. For example, [this developer tool](https://github.com/stanleyrya/scriptable-script-updater) updates scripts using Github. By storing the parameters in a file you won't have to go into the file and rewrite your parameters each time the file is downloaded/updated again. 37 | * This is also useful for sensitive information (API key). 38 | 3. Hard-coded parameters at the top of the file. 39 | 40 | ## Common Problems 41 | 42 | ### "Error: Cannot parse response to an image." 43 | 44 | This is most typically an issue with Google Maps' account settings. If you copy-paste the Google Maps URL to your browser you will likely see this message: 45 | 46 | "The Google Maps Platform server rejected your request. You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started" 47 | 48 | We'll attempt to add better logs at some point in the future 👍. 49 | 50 | ## Debugging Tools 51 | 52 | There are three useful tools for debugging built-in to this script. They can all be turned on by setting their parameter to true. They are: 53 | 54 | 1. forceWidgetView: Loads the widget even if run directly from scriptable. Useful for seeing the widget view's logs. 55 | 2. writeLogsIfException: Writes the script's logs to a file if there is an exception. Be careful, right now it will overrite the file every time there is an exception. 56 | 3. logPerformanceMetrics: Stores function performance metrics each time the script runs. Appends how long each function takes in milliseconds to a CSV if they are wrapped by the performanceWrapper. 57 | 58 | ### Failure Logs 59 | If turned on, the script will write it's logs to the file system whenever it encounters a failure. The logs of the script are stored in the scriptable folder under `storage/scriptname-logs.txt`. 60 | 61 | Please note that the logs will be overwritten each time there is a new failure if this feature is turned on. 62 | 63 | [Here's an issue where the failure logs where useful.](https://github.com/bring-larry-to-life/scriptable-widget-interest-map/issues/12) 64 | 65 | ### Performance Metrics 66 | If turned on, performance metrics are stored in a CSV file. They can be found in the scriptable folder under `storage/scriptname-performance-metrics.csv`. 67 | 68 | CSV files could be read directly or visualized in Excel and Google Sheets. They can also be read easily using the [Charty](https://chartyios.app/) app with this shortcut: 69 | 70 | https://www.icloud.com/shortcuts/932366757e124075ae6f755da89563eb 71 | 72 |

73 | 74 |

75 | 76 | Here's an investigation where the performance logs were useful: 77 | 78 | | Performance Graph | Investigation | 79 | | --- | --- | 80 | | ![A graph depicting getCurrentLocation taking much longer than the other APIs](media/BB6E2934-E843-4F2F-9668-3C4890FA22DD.png?raw=true "getCurrentLocation Latency with 10 meter accuracy") | In this graph we noticed that getCurrentLocation with 10 meter accuracy would occasionally take a long time to execute. This was surprising because other apps seem to get the current location quickly and the latency is inconsistent. | 81 | | ![A graph depicting getCurrentLocation taking less time consistently after being set to 100 meters. The other APIs have a blip with higher latency but that's believed to be related to internet access.](media/94455C7B-176B-4DA3-8754-A4CDC5AB482A.png?raw=true "getCurrentLocation Latency with 100 meter accuracy in the second half") | We modified getCurrentLocation to use 100 meter accuracy and not only did it's latency drop considerably but it stayed consistent. What's interesting is now the other APIs spiked. It's unlikely that both Wikipedia and Google Maps had issues at the same time so we believe the latency spikes were caused by a bug or an issue local to the phone running the script. Our current theory is that the widget was run from inside a car that was trying to connect to a house's wifi causing a bad internet connection. | 82 | | ![A graph depicting all APIs with normal latency.](media/B6B02EBA-BCE4-45BC-A7B1-15C5B5363CBF.png?raw=true "APIs are back to normal latency") | After additional testing the spikes have not occurred again. Everything looks normal! | 83 | -------------------------------------------------------------------------------- /media/0F9651FC-E5F9-43FD-A1A5-5FA6B1FF395D.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bring-larry-to-life/scriptable-widget-interest-map/35fe1a7bd7d9293bef050675e68cb0e037384e13/media/0F9651FC-E5F9-43FD-A1A5-5FA6B1FF395D.gif -------------------------------------------------------------------------------- /media/3DFC39F6-962E-4255-9337-DBAD908AAAC6.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bring-larry-to-life/scriptable-widget-interest-map/35fe1a7bd7d9293bef050675e68cb0e037384e13/media/3DFC39F6-962E-4255-9337-DBAD908AAAC6.jpeg -------------------------------------------------------------------------------- /media/94455C7B-176B-4DA3-8754-A4CDC5AB482A.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bring-larry-to-life/scriptable-widget-interest-map/35fe1a7bd7d9293bef050675e68cb0e037384e13/media/94455C7B-176B-4DA3-8754-A4CDC5AB482A.png -------------------------------------------------------------------------------- /media/B6B02EBA-BCE4-45BC-A7B1-15C5B5363CBF.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bring-larry-to-life/scriptable-widget-interest-map/35fe1a7bd7d9293bef050675e68cb0e037384e13/media/B6B02EBA-BCE4-45BC-A7B1-15C5B5363CBF.png -------------------------------------------------------------------------------- /media/BB6E2934-E843-4F2F-9668-3C4890FA22DD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bring-larry-to-life/scriptable-widget-interest-map/35fe1a7bd7d9293bef050675e68cb0e037384e13/media/BB6E2934-E843-4F2F-9668-3C4890FA22DD.png -------------------------------------------------------------------------------- /media/C9BF6F28-93CC-4F8F-A848-58FD1CDB901B.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bring-larry-to-life/scriptable-widget-interest-map/35fe1a7bd7d9293bef050675e68cb0e037384e13/media/C9BF6F28-93CC-4F8F-A848-58FD1CDB901B.png -------------------------------------------------------------------------------- /media/D43ECEA3-0EF5-494B-A668-9954258A37D5.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bring-larry-to-life/scriptable-widget-interest-map/35fe1a7bd7d9293bef050675e68cb0e037384e13/media/D43ECEA3-0EF5-494B-A668-9954258A37D5.gif -------------------------------------------------------------------------------- /widget.js: -------------------------------------------------------------------------------- 1 | // Variables used by Scriptable. 2 | // These must be at the very top of the file. Do not edit. 3 | // icon-color: deep-gray; icon-glyph: map; 4 | 5 | /* 6 | * Authors: Ryan Stanley (stanleyrya@gmail.com), Jason Morse (jasonkylemorse@gmail.com) 7 | * Description: Scriptable code to display Google Maps image widget with nearby points of 8 | * interest, sourced from Wikipedia. Clicking on the map opens a list of locations with photos, 9 | * titles, and quick links to Wikipedia and Google Maps directions. 10 | */ 11 | 12 | /** 13 | * Class that can read and write JSON objects using the file system. 14 | * 15 | * This is a minified version but it can be replaced with the full version by copy pasting this code! 16 | * https://github.com/stanleyrya/scriptable-playground/blob/main/json-file-manager/json-file-manager.js 17 | * 18 | * Usage: 19 | * * write(relativePath, jsonObject): Writes JSON object to a relative path. 20 | * * read(relativePath): Reads JSON object from a relative path. 21 | */ 22 | class JSONFileManager{write(e,r){const t=this.getFileManager(),i=this.getCurrentDir()+e,l=e.split("/");if(l>1){const e=l[l.length-1],r=i.replace("/"+e,"");t.createDirectory(r,!0)}if(t.fileExists(i)&&t.isDirectory(i))throw"JSON file is a directory, please delete!";t.writeString(i,JSON.stringify(r))}read(e){const r=this.getFileManager(),t=this.getCurrentDir()+e;if(!r.fileExists(t))throw"JSON file does not exist! Could not load: "+t;if(r.isDirectory(t))throw"JSON file is a directory! Could not load: "+t;r.downloadFileFromiCloud(t);const i=JSON.parse(r.readString(t));if(null!==i)return i;throw"Could not read file as JSON! Could not load: "+t}getFileManager(){try{return FileManager.iCloud()}catch(e){return FileManager.local()}}getCurrentDir(){const e=this.getFileManager(),r=module.filename;return r.replace(e.fileName(r,!0),"")}} 23 | const jsonFileManager = new JSONFileManager(); 24 | 25 | /** 26 | * Class that can write logs to the file system. 27 | * 28 | * This is a minified version but it can be replaced with the full version by copy pasting this code! 29 | * https://github.com/stanleyrya/scriptable-playground/blob/main/file-logger/file-logger.js 30 | * 31 | * Usage: 32 | * * log(line): Adds the log line to the class' internal log object. 33 | * * writeLogs(relativePath): Writes the stored logs to the relative file path. 34 | */ 35 | class FileLogger{constructor(){this.logs=""}log(e){e instanceof Error?console.error(e):console.log(e),this.logs+=new Date+" - "+e+"\n"}writeLogs(e){const r=this.getFileManager(),t=this.getCurrentDir()+e,i=e.split("/");if(i>1){const e=i[i.length-1],l=t.replace("/"+e,"");r.createDirectory(l,!0)}if(r.fileExists(t)&&r.isDirectory(t))throw"Log file is a directory, please delete!";r.writeString(t,this.logs)}getFileManager(){try{return FileManager.iCloud()}catch(e){return FileManager.local()}}getCurrentDir(){const e=this.getFileManager(),r=module.filename;return r.replace(e.fileName(r,!0),"")}} 36 | const logger = new FileLogger(); 37 | 38 | /** 39 | * Class that can capture the time functions take in milliseconds then export them to a CSV. 40 | * 41 | * This is a minified version but it can be replaced with the full version by copy pasting this code! 42 | * https://github.com/stanleyrya/scriptable-playground/blob/main/performance-debugger/performance-debugger.js 43 | * 44 | * Usage: 45 | * * wrap(fn, args): Wrap the function calls you want to monitor with this wrapper. 46 | * * appendPerformanceDataToFile(relativePath): Use at the end of your script to write the metrics to the CSV file at the relative file path. 47 | */ 48 | class PerformanceDebugger{constructor(){this.performanceResultsInMillis={}}async wrap(e,t){const r=Date.now(),i=await e.apply(null,t),s=Date.now();return this.performanceResultsInMillis[e.name]=s-r,i}appendPerformanceDataToFile(e){const t=this.getFileManager(),r=this.getCurrentDir()+e,i=e.split("/");if(i>1){const e=i[i.length-1],s=r.replace("/"+e,"");t.createDirectory(s,!0)}if(t.fileExists(r)&&t.isDirectory(r))throw"Performance file is a directory, please delete!";let s,n,l=Object.getOwnPropertyNames(this.performanceResultsInMillis);if(t.fileExists(r)){console.log("File exists, reading headers. To keep things easy we're only going to write to these headers."),t.downloadFileFromiCloud(r),n=t.readString(r),s=this.getFirstLine(n).split(",")}else console.log("File doesn't exist, using available headers."),n=(s=l).toString();n=n.concat("\n");for(const e of s)this.performanceResultsInMillis[e]&&(n=n.concat(this.performanceResultsInMillis[e])),n=n.concat(",");n=n.slice(0,-1),t.writeString(r,n)}getFirstLine(e){var t=e.indexOf("\n");return-1===t&&(t=void 0),e.substring(0,t)}getFileManager(){try{return FileManager.iCloud()}catch(e){return FileManager.local()}}getCurrentDir(){const e=this.getFileManager(),t=module.filename;return t.replace(e.fileName(t,!0),"")}} 49 | const performanceDebugger = new PerformanceDebugger(); 50 | 51 | /* 52 | * Parameters 53 | * 54 | * apiKey: [REQUIRED] The Google Maps API Key. 55 | * forceWidgetView: Loads the widget even if run directly from scriptable. Useful for seeing the widget view's logs. 56 | * writeLogsIfException: Writes the script's logs to a file if there is an exception. Be careful, right now it will overrite the file every time there is an exception. 57 | * logPerformanceMetrics: Stores function performance metrics each time the script runs. Appends how long each function takes in milliseconds to a CSV if they are wrapped by the performanceWrapper. 58 | * 59 | * Attempts to load parameters in this order: 60 | * 1. Widget parameters 61 | * 2. JSON file "./storage/scriptname.json" 62 | * 3. Hard-coded parameters right here: 63 | */ 64 | const scriptParams = { 65 | apiKey: 'XXX', 66 | forceWidgetView: false, 67 | writeLogsIfException: false, 68 | logPerformanceMetrics: false, 69 | overrideLatitude: 42.3549970, 70 | overrideLongitude: -71.0644556 71 | } 72 | 73 | const widgetParams = args.widgetParameter ? JSON.parse(args.widgetParameter) : undefined; 74 | 75 | let storedParams; 76 | try { 77 | storedParams = jsonFileManager.read("storage/" + Script.name() + ".json"); 78 | } catch (err) { 79 | logger.log(err); 80 | } 81 | 82 | const params = widgetParams || storedParams || scriptParams; 83 | const { apiKey } = params; 84 | 85 | // Refresh interval in hours 86 | const refreshInterval = 6; 87 | 88 | /******************************* 89 | ****** UTILITY FUNCTIONS ****** 90 | *******************************/ 91 | 92 | // Get user's current latitude and longitude 93 | const getCurrentLocation = async() => { 94 | await Location.setAccuracyToHundredMeters(); 95 | return Location.current().then((res) => { 96 | return { 97 | 'latitude': res.latitude, 98 | 'longitude': res.longitude 99 | }; 100 | }, err => log(err)); 101 | }; 102 | 103 | /* 104 | * Given coordinates, return a description of the current location in words (town name, etc.). 105 | * Object returned has two properties: 106 | * { 107 | * "areaOfInterest": "Spot Pond - Middlesex Fells Reservation", 108 | * "generalArea": "Medford, MA" 109 | * } 110 | * 111 | * More information here: https://github.com/stanleyrya/scriptable-playground/blob/main/reverse-geocode-tests.js 112 | */ 113 | const getLocationDescription = async(location) => { 114 | return Location.reverseGeocode(location.latitude, location.longitude).then((res) => { 115 | const response = res[0]; 116 | 117 | let areaOfInterest = ""; 118 | if (response.inlandWater) { 119 | areaOfInterest += response.inlandWater 120 | } else if (response.ocean) { 121 | areaOfInterest += response.ocean; 122 | } 123 | if (areaOfInterest && response.areasOfInterest) { 124 | areaOfInterest += ' - '; 125 | } 126 | if (response.areasOfInterest) { 127 | // To keep it simple, just grab the first one. 128 | areaOfInterest += response.areasOfInterest[0]; 129 | } 130 | 131 | let generalArea = ""; 132 | if (response.locality) { 133 | generalArea += response.locality; 134 | } 135 | if (generalArea && response.administrativeArea) { 136 | generalArea += ', '; 137 | } 138 | if (response.administrativeArea) { 139 | generalArea += response.administrativeArea; 140 | } 141 | 142 | return { 143 | areaOfInterest: areaOfInterest ? areaOfInterest : null, 144 | generalArea: generalArea ? generalArea : null 145 | }; 146 | }, err => log(`Could not reverse geocode location: ${err}`)); 147 | }; 148 | 149 | // Utility function to increment alphabetically for map markers 150 | const nextChar = (c) => { 151 | return String.fromCharCode(c.charCodeAt(0) + 1); 152 | } 153 | 154 | /******************************* 155 | **** GOOGLE MAPS FUNCTIONS **** 156 | *******************************/ 157 | 158 | // Endpoint for Static Google Maps API 159 | const googleMapsBaseUri = 'https://maps.googleapis.com/maps/api/staticmap'; 160 | 161 | /* 162 | * Gets the maps size for Google Maps' static API. 163 | * Returns the size for a square by default. 164 | */ 165 | const getMapSize = (widgetSize) => { 166 | if (widgetSize === 'medium') { 167 | return '800x500' 168 | } else { 169 | return '800x800' 170 | } 171 | } 172 | 173 | // Construct Google Maps API URI given city input 174 | const getMapUrlByCity = (apiKey, city, zoom = '14') => `${googleMapsBaseUri}?center=${city}&zoom=${zoom}&size=${size}&key=${apiKey}`; 175 | 176 | // Construct Google Maps API URI given user latitude, longitude, and list of markers 177 | const getMapUrlByCoordinates = (apiKey, userLat, userLng, markers = [], zoom = '14', size = '800x800') => { 178 | const center = `${userLat},${userLng}`; 179 | if (markers.length >= 1) { 180 | let label = '@'; 181 | const coords = markers.map(marker => { 182 | label = nextChar(label); 183 | return `markers=color:red|label:${label}|${marker.lat},${marker.lng}`; 184 | }); 185 | return `${googleMapsBaseUri}?size=${size}&key=${apiKey}&${coords.join('&')}`; 186 | } 187 | return `${googleMapsBaseUri}?center=${center}&zoom=${zoom}&size=${size}&key=${apiKey}&markers=color:blue|${center}`; 188 | } 189 | 190 | // Returns object containing static Google Maps image response (by city) and widget title 191 | async function getMapsPicByCity(apiKey, city) { 192 | try { 193 | logger.log('Request URI'); 194 | logger.log(getMapUrlByCity(apiKey, city)); 195 | const mapPicRequest = new Request(encodeURI(getMapUrlByCity(apiKey, city))); 196 | const mapPic = await mapPicRequest.loadImage(); 197 | return { image: mapPic, title: city }; 198 | } catch (e) { 199 | logger.log(e) 200 | return null; 201 | } 202 | } 203 | 204 | // Returns object containing static Google Maps image response (by specific location & markers) 205 | async function getMapsPicByCurrentLocations(apiKey, location, markers) { 206 | try { 207 | const uri = getMapUrlByCoordinates(apiKey, location.latitude, location.longitude, markers); 208 | logger.log('Request URI'); 209 | logger.log(uri); 210 | const mapPicRequest = new Request(encodeURI(uri)); 211 | return await mapPicRequest.loadImage(); 212 | } catch (e) { 213 | logger.log("Copy-paste the Google Maps URI into Safari if this doesn't work. There is probably something wrong with the API key."); 214 | throw e; 215 | } 216 | } 217 | 218 | // Returns Google Maps directions direct link from current location to point of interest 219 | const getDirectionsUrl = (location, destination) => `https://www.google.com/maps/dir/${location.latitude},${location.longitude}/${destination.latitude},${destination.longitude}`; 220 | 221 | // Returns Google Maps direct link for point of interest 222 | const getCoordsUrl = (destination) => `https://www.google.com/maps/search/?api=1&query=${destination.latitude},${destination.longitude}`; 223 | 224 | /******************************* 225 | ***** WIKIPEDIA FUNCTIONS ***** 226 | *******************************/ 227 | 228 | const getWikiUrlByPageId = (pageId) => `https://en.wikipedia.org/?curid=${pageId}`; 229 | const getWikiUrlByCoords = (lat, lng) => `https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates|pageimages&generator=geosearch&ggscoord=${lat}|${lng}&ggsradius=10000`; 230 | 231 | /* 232 | * Calls wikipedia for nearby articles and modifies the object for ease of use. 233 | * Returns an empty array if there are no results or if there is a failure. 234 | * 235 | * Example Wikipedia API: 236 | * https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates%7Cpageimages&generator=geosearch&ggscoord=41.68365535753726|-70.19823287890266&ggsradius=10000 237 | * 238 | * Useful Wikipedia article on how to use API with location and images: 239 | * https://www.mediawiki.org/wiki/API:Geosearch#Example_3:_Search_for_pages_nearby_with_images 240 | * 241 | * Useful StackOverflow article about using Wikipedia API with location and images: 242 | * https://stackoverflow.com/questions/24529853/how-to-get-more-info-within-only-one-geosearch-call-via-wikipedia-api 243 | * 244 | * Example output from Wikipedia: 245 | * {"batchcomplete":"","query":{"pages":{"38743":{"pageid":38743,"ns":0,"title":"Cape Cod","index":-1,"coordinates":[{"lat":41.68,"lon":-70.2,"primary":"","globe":"earth"}],"thumbnail":{"source":"https://upload.wikimedia.org/wikipedia/en/thumb/1/12/Ccnatsea.jpg/50px-Ccnatsea.jpg","width":50,"height":34},"pageimage":"Ccnatsea.jpg"}}}} 246 | * 247 | * Example output: [{ 248 | * lat: 41.68 249 | * lng: -70.2 250 | * thumbnail: {source: "https://upload.wikimedia.org/wikipedia/en/thumb/1/12/Ccnatsea.jpg/50px-Ccnatsea.jpg", width: 50, height: 34} 251 | * title: "Cape Cod", 252 | * url: https://en.wikipedia.org/?38743 253 | * }] 254 | */ 255 | async function getNearbyWikiArticles(location) { 256 | try { 257 | const uri = getWikiUrlByCoords(location.latitude, location.longitude); 258 | logger.log('Request URI: ' + uri); 259 | const request = new Request(encodeURI(uri)); 260 | const wikiJSON = await request.loadJSON(); 261 | 262 | let articles; 263 | if (wikiJSON && wikiJSON.query && wikiJSON.query.pages) { 264 | articles = wikiJSON.query.pages; 265 | } else { 266 | throw new Error("Could not read data from wikipedia"); 267 | } 268 | 269 | var response = Object.values(articles).map(article => ({ 270 | "url": getWikiUrlByPageId(article.pageid), 271 | "title": article.title, 272 | "lng": article.coordinates[0].lon, 273 | "lat": article.coordinates[0].lat, 274 | "thumbnail": article.thumbnail 275 | })); 276 | return response; 277 | } catch (e) { 278 | logger.log(e); 279 | return []; 280 | } 281 | } 282 | 283 | /***************************************** 284 | ***** SCRIPTABLE & WIDGET FUNCTIONS ***** 285 | *****************************************/ 286 | 287 | const createTable = (map, items) => { 288 | const table = new UITable(); 289 | const mapRow = new UITableRow(); 290 | const mapCell = mapRow.addImage(map); 291 | mapCell.widthWeight = 100; 292 | mapRow.dismissOnSelect = false; 293 | mapRow.height = 400; 294 | table.addRow(mapRow); 295 | let label = 'A'; 296 | items.forEach(item => { 297 | logger.log('ITEM'); 298 | logger.log(item); 299 | const row = new UITableRow(); 300 | const markerUrl = `http://maps.google.com/mapfiles/kml/paddle/${label}.png`; 301 | const imageUrl = item.thumbnail ? item.thumbnail.source : ''; 302 | const title = item.title; 303 | const markerCell = row.addButton(label); 304 | const imageCell = row.addImageAtURL(imageUrl); 305 | const titleCell = row.addText(title); 306 | markerCell.onTap = () => Safari.open(getCoordsUrl({ latitude: item.lat, longitude: item.lng })); 307 | markerCell.widthWeight = 10; 308 | imageCell.widthWeight = 20; 309 | titleCell.widthWeight = 50; 310 | row.height = 60; 311 | row.cellSpacing = 10; 312 | row.onSelect = () => Safari.open(item.url); 313 | row.dismissOnSelect = false; 314 | table.addRow(row); 315 | label = nextChar(label); 316 | }); 317 | return table; 318 | } 319 | 320 | async function createWidget(location) { 321 | let widget = new ListWidget(); 322 | let wikiArticles = await performanceDebugger.wrap(getNearbyWikiArticles, [location]); 323 | // let image = await performanceDebugger.wrap(getMapsPicByCity, [apiKey, 'Boston, MA']); 324 | let image = await performanceDebugger.wrap(getMapsPicByCurrentLocations, [apiKey, location, wikiArticles]); 325 | widget.backgroundImage = image; 326 | 327 | let startColor = new Color("#1c1c1c00"); 328 | let endColor = new Color("#1c1c1cb4"); 329 | let gradient = new LinearGradient(); 330 | gradient.colors = [startColor, endColor]; 331 | gradient.locations = [0.25, 1]; 332 | widget.backgroundGradient = gradient; 333 | widget.backgroundColor = new Color("1c1c1c"); 334 | 335 | let textStack = widget.addStack(); 336 | textStack.layoutHorizontally(); 337 | textStack.bottomAlignContent(); 338 | 339 | let titleStack = textStack.addStack(); 340 | titleStack.layoutVertically(); 341 | titleStack.bottomAlignContent(); 342 | titleStack.addSpacer(); 343 | 344 | textStack.addSpacer(); 345 | 346 | let additionalInfoStack = textStack.addStack(); 347 | additionalInfoStack.layoutVertically(); 348 | additionalInfoStack.bottomAlignContent(); 349 | additionalInfoStack.addSpacer(); 350 | 351 | let currentLocationDescription = await getLocationDescription(location); 352 | let primaryLocationDescription; 353 | let secondaryLocationDescription; 354 | if (currentLocationDescription.areaOfInterest) { 355 | primaryLocationDescription = currentLocationDescription.areaOfInterest; 356 | secondaryLocationDescription = currentLocationDescription.generalArea ? currentLocationDescription.generalArea : null; 357 | } else if (currentLocationDescription.generalArea) { 358 | primaryLocationDescription = currentLocationDescription.generalArea; 359 | } 360 | 361 | let primaryTitleText = titleStack.addText(primaryLocationDescription); 362 | primaryTitleText.leftAlignText(); 363 | primaryTitleText.textColor = Color.white(); 364 | if (secondaryLocationDescription) { 365 | let secondaryTitleText = titleStack.addText(secondaryLocationDescription); 366 | secondaryTitleText.font = Font.thinSystemFont(12); 367 | secondaryTitleText.textColor = Color.white(); 368 | secondaryTitleText.leftAlignText(); 369 | } 370 | 371 | let sourceText = additionalInfoStack.addText("Wikipedia"); 372 | sourceText.font = Font.thinSystemFont(12); 373 | sourceText.textColor = Color.white(); 374 | sourceText.rightAlignText(); 375 | 376 | let lastUpdatedDate = additionalInfoStack.addDate(new Date()); 377 | lastUpdatedDate.applyTimeStyle(); 378 | lastUpdatedDate.font = Font.thinSystemFont(12); 379 | lastUpdatedDate.textColor = Color.white(); 380 | lastUpdatedDate.rightAlignText(); 381 | 382 | let interval = 1000 * 60 * 60 * refreshInterval; 383 | widget.refreshAfterDate = new Date(Date.now() + interval); 384 | 385 | return widget; 386 | } 387 | 388 | async function clickWidget(location) { 389 | let wikiArticles = await performanceDebugger.wrap(getNearbyWikiArticles, [location]); 390 | let image = await performanceDebugger.wrap(getMapsPicByCurrentLocations, [apiKey, location, wikiArticles]); 391 | const table = createTable(image, wikiArticles); 392 | await QuickLook.present(table); 393 | } 394 | 395 | async function run() { 396 | if (params) { 397 | logger.log("Using params: " + JSON.stringify(params)); 398 | } else { 399 | logger.log("No valid parameters!"); 400 | return; 401 | } 402 | 403 | if (!params.apiKey || params.apiKey === 'XXX') { 404 | logger.log("You must provide an API Key from Google to use this script."); 405 | return; 406 | } 407 | 408 | let location; 409 | if (params.overrideLatitude && params.overrideLongitude) { 410 | location = { 411 | latitude: params.overrideLatitude, 412 | longitude: params.overrideLongitude 413 | } 414 | } else { 415 | location = await performanceDebugger.wrap(getCurrentLocation); 416 | } 417 | 418 | if (config.runsInWidget) { 419 | const widget = await createWidget(location); 420 | Script.setWidget(widget); 421 | Script.complete(); 422 | 423 | } else if (params.forceWidgetView) { 424 | // Useful for loading widget and seeing logger.logs manually 425 | const widget = await createWidget(location); 426 | await widget.presentMedium(); 427 | 428 | } else { 429 | await clickWidget(location); 430 | } 431 | 432 | if (params.logPerformanceMetrics) { 433 | performanceDebugger.appendPerformanceDataToFile("storage/" + Script.name() + "-performance-metrics.csv"); 434 | } 435 | } 436 | 437 | try { 438 | await run(); 439 | } catch (err) { 440 | logger.log(err); 441 | if (params.writeLogsIfException) { 442 | logger.writeLogs("storage/" + Script.name() + "-logs.txt") 443 | } 444 | throw err; 445 | } 446 | --------------------------------------------------------------------------------