Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: geolocation

geoCodingLibで逆住所ジオコーディング

Posted on 3月 16 by Takaaki Naganoya

逆住所ジオコーディング(住所→緯度経度)/逆住所ジオコーディング(緯度経度→住所)のための、よくありがちなObjective-CのコードをCocoa Framework化した「geoCodingLib」を呼び出して、逆住所ジオコーディングを行うAppleScriptです。

Cocoa Frameworkを呼び出すため、実行にはScript Debuggerあるいは同ソフトから書き出した拡張アプレット環境が必要です。Apple純正のスクリプトエディタでは実行できません。

–> geoCodingLib.framework(Universal Binary)

AppleScript名:geoCodingLibで逆住所ジオコーディング.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/03/16
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "CoreLocation"
use framework "geoCodingLib"
use scripting additions

set aLat to 35.7356786
set aLong to 139.6516811
set aLoc to current application’s CLLocation’s alloc()’s initWithLatitude:(aLat) longitude:(aLong)
set aRes to my getAddressOf:aLoc
–> 東京都練馬区豊玉北6丁目12-1

–緯度経度→住所
on getAddressOf:aLocation
  set aGeo to current application’s geocodingLib’s alloc()’s init()
  
aGeo’s getAddress:aLocation
  
  
delay 1.0E-4
  
  
repeat 1000 times
    delay 1.0E-4
    
set aRes to aGeo’s placeAddress()
    
if aRes is not equal to missing value then exit repeat
  end repeat
  
  
if aRes is equal to missing value then return false
  
return aRes as string
end getAddressOf:

★Click Here to Open This Script 

(Visited 8 times, 1 visits today)
Posted in geolocation | Tagged 13.0savvy CoreLocation | Leave a comment

geoCodingLibで住所ジオコーディング

Posted on 3月 16 by Takaaki Naganoya

住所ジオコーディング(住所→緯度経度)/逆住所ジオコーディング(緯度経度→住所)のための、よくありがちなObjective-CのコードをCocoa Framework化した「geoCodingLib」を呼び出して、住所ジオコーディングを行うAppleScriptです。

Cocoa Frameworkを呼び出すため、実行にはScript Debuggerあるいは同ソフトから書き出した拡張アプレット環境が必要です。Apple純正のスクリプトエディタでは実行できません。

–> geoCodingLib.framework(Universal Binary)

AppleScript名:geoCodingLibで住所ジオコーディング.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/03/16
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "CoreLocation"
use framework "geoCodingLib"
use scripting additions

set aRes to my getGeoInfo:"東京都練馬区豊玉北6丁目12-1"
if aRes = false then return
return aRes –> {35.7356786, 139.6516811}

–住所→緯度経度
on getGeoInfo:addressText
  set aGeo to current application’s geocodingLib’s alloc()’s init()
  
aGeo’s getLatLong:addressText
  
  
delay 1.0E-3
  
  
repeat 1000 times
    delay 1.0E-3
    
set aRes to aGeo’s placemarksArray()
    
if aRes is not equal to missing value then exit repeat
  end repeat
  
  
if aRes is equal to missing value then return false
  
  
set aaRes to first item of aRes
  
set theDescription to aaRes’s |description|()
  
set theName to aaRes’s |name|() –> "河辺町x丁目XX-X"
  
set theCountry to aaRes’s country() –> "日本"
  
set thePostal to aaRes’s postalCode() –> "198-00XX"
  
set theAdminarea to aaRes’s administrativeArea() –> "東京都"
  
set theSubAdmin to aaRes’s subAdministrativeArea() –> (null)
  
set theLocality to aaRes’s locality() –> "青梅市"
  
set theSubLocality to aaRes’s subLocality() –> "河辺町"
  
set theThoroughfare to aaRes’s thoroughfare() –>"河辺町x丁目"
  
set theSubThoroughfare to aaRes’s subThoroughfare() –>"XX-X"
  
set theTZ to aaRes’s timeZone() –> "Asia/Tokyo (JST) offset 32400"
  
set theRegion to aaRes’s region() –> CLCircularRegion (identifier:’<+35.xxxxx,+139.xxxxx> radius 70.64’, center:<+35.xxxxx,+139.xxxxx0>, radius:70.64m)
  
set theRegCenter to theRegion’s |center|()
  
set aLat to theRegCenter’s latitude
  
set aLng to theRegCenter’s longitude
  
  
return {aLat, aLng}
end getGeoInfo:

★Click Here to Open This Script 

(Visited 11 times, 1 visits today)
Posted in geolocation | Tagged 13.0savvy CoreLocation | Leave a comment

指定緯度における1km相当の経度の大きさを求める

Posted on 12月 15, 2019 by Takaaki Naganoya

指定緯度における1kmあたりの経度の角度などを計算するAppleScriptです。Rubyのコードで書かれたものがあったので、AppleScriptに翻訳してみました。

三角関数を用いるため、関数計算ライブラリ「calcLibAS」を併用しています。

なんでこんな計算をすることになったかといえば、Apple Mapsの仕様で、地図表示エリアの指定時に表示距離ではなく表示角度(spn)が要求されるようなので、計算方法を求めておいたという次第です。

AppleScript名:1kmあたりの経度の大きさを求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/15
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use calcLib : script "calcLibAS"

–参照:1kmあたりの経度の大きさ
–https://github.com/ryym/google-maps-demo/blob/master/note.md
set aLat to 31.5719562 –鹿児島の緯度
set aDeg to calc1kmDegreeinLatitude(aLat) of me –経度方向(横)に1kmに相当する角度
–> 0.010543813284

set bDeg to calc100mDegreeinLatitude(aLat) of me –経度方向(横)に100mに相当する角度
–> 0.001054381328

set aLat to 35.73993521 –練馬の緯度
set aDeg to calc1kmDegreeinLatitude(aLat) of me –経度方向(横)に1kmに相当する角度
–> 0.011067403977

set bDeg to calc100mDegreeinLatitude(aLat) of me –経度方向(横)に100mに相当する角度
–> 0.001106740398

–1kmあたりの緯度の大きさ
set eRes to calc1kmDegreeinLong() of me –緯度方向(縦)に1kmに相当する角度
–> 0.008983152841

set eRes to calc100mDegreeinLong() of me –緯度方向(縦)に100mに相当する角度
–> 8.98315284119522E-4

–指定緯度における1km相当の経度の角度
on calc1kmDegreeinLatitude(aLat)
  set eRadius to 6378.137 –in km
  
set r to eRadius * (cos (aLat * pi / 180))
  
set cm to 2 * pi * r
  
set kd to 360 / cm
  
return kd
end calc1kmDegreeinLatitude

–指定緯度における1km相当の経度の角度
on calc100mDegreeinLatitude(aLat)
  set eRadius to 6378.137 –in km
  
set r to eRadius * (cos (aLat * pi / 180))
  
set cm to 2 * pi * r
  
set kd to 360 / cm
  
return kd / 10
end calc100mDegreeinLatitude

–1km相当の緯度の角度
on calc1kmDegreeinLong()
  set eRadius to 6378.137 –in km
  
set pc to 2 * pi * eRadius
  
set dLat to 360 / pc
  
return dLat
end calc1kmDegreeinLong

–100m相当の緯度の角度
on calc100mDegreeinLong()
  return calc1kmDegreeinLong() / 10
end calc100mDegreeinLong

★Click Here to Open This Script 

(Visited 234 times, 3 visits today)
Posted in geolocation Number | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy Maps | Leave a comment

map scripter script Library

Posted on 12月 14, 2019 by Takaaki Naganoya

macOS添付の地図.app(Maps.app)をAppleScript的な用語で操作するAppleScriptライブラリ「map scripter」の配布を開始しました。macOS 10.10以降(作成+動作確認は10.14)で、動作するはずです。

–> Download mapScripter(To ~/Library/Script Libraries)

Maps.appのコントロールは非同期のURL Eventsで行われるため、本ライブラリを通じてMaps.appを操作しても、macOSの「セキュリティ」ダイアログは表示されません。そのかわり、100%操作できるという保証もありません(時間帯によって処理要求が返ってこなかったりします。とくに、グルメ系検索)。また、Maps.appの実行のためにインターネット接続が必須です。

Maps.appは外部からURL Eventのみでコントロール可能なアプリケーションです。操作の方法がエキセントリックすぎるので、一般的なAppleScript対応アプリケーションと同様の英語的な用語でアクセスできるようにしてみました。例によって、実行結果イメージやサンプルScriptをsdefの中に入れてあります。

macOS 10.15.2上で動作させたときに、「display around here」コマンドが、

のようなエラーを表示することがあります。これは、どうも位置情報サービスに要求を出したのに拒否されたという種類のOS側のエラーのようで、システム環境設定の「セキュリティとプライバシー」>「プライバシー」>「位置情報サービス」のあたりで認証が行われなくてはならないはずのもの(認証済み)が、エラーを起こしているようで、、、、macOS側のバグと言っていい挙動だと思います。

Maps.app以外でも、AppleScript系の機能実装がおかしいApple純正のアプリケーションに対し、Framework経由でデータアクセスするようなライブラリがあると便利かもしれませんが、そこまでやったらフリー配布はちょっと勘弁してほしい感じがします。

AppleScript名:display map by address.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/14
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use mapLib : script "map scripter"

display map by address "東京都港区六本木6丁目10番1号" map type normal zoom level 25

★Click Here to Open This Script 

AppleScript名:display map route.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/14
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use mapLib : script "map scripter"

display map route from "豊島園" to "目黒" using public

★Click Here to Open This Script 

AppleScript名:display point.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/14
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use mapLib : script "map scripter"

display point query "レストラン" latitude 31.5719562 longitude 130.56257084

★Click Here to Open This Script 

AppleScript name:display around here.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/14
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use mapLib : script "map scripter"

display around here query "ラーメン"

★Click Here to Open This Script 

com.apple.Maps

(Visited 113 times, 1 visits today)
Posted in geolocation | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy Maps | Leave a comment

アラートダイアログ上のWebViewに世界地図を表示 v2b

Posted on 11月 20, 2019 by Takaaki Naganoya

世界地図のSVGをHTMLReader.frameworkでparseして、目的のノードに塗り色の指定を行い、WkWebView上で表示するAppleScriptです。

–> Download selectCountry2(Code-signed AppleScript executable applet)

昨日のものがあくまでSVGのParseと表示が目的の試作品であったのに対し、本Scriptは連続してポップアップメニューから対象を選んで表示するというものです。

同様にmacOS 10.15.1上で作成しましたが、このバージョンのOS環境ではAppleScriptアプレットにFrameworkを入れてAppleScript内から呼び出すことが標準のランタイム(Script Editorから書き出した場合)では行えないようになっており、Script Debuggerから「Application(Enhanced)」で書き出さないと呼び出せないようです(これはちょっとひどいかも、、、、)。

世界地図はWikipediaから拾ってきたもので、ISO国コードではなく名称でIDが振ってあり、日本もJapanではなくHokkaido、Honshu、Shikoku、Kyushuuに分けて登録されています。


▲Script Editor上でサードパーティFramework呼び出しの動作ができているのは、この実行環境でSIPを解除してあるからです

AppleScript名:アラートダイアログ上のWebViewに世界地図を表示 v2b.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/11/18
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "HTMLReader" –https://github.com/nolanw/HTMLReader
use framework "WebKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property WKWebView : a reference to current application’s WKWebView
property WKUserScript : a reference to current application’s WKUserScript
property NSURLRequest : a reference to current application’s NSURLRequest
property HTMLDocument : a reference to current application’s HTMLDocument
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property WKUserContentController : a reference to current application’s WKUserContentController
property WKWebViewConfiguration : a reference to current application’s WKWebViewConfiguration
property WKUserScriptInjectionTimeAtDocumentEnd : a reference to current application’s WKUserScriptInjectionTimeAtDocumentEnd

property theResult : 0
property returnCode : 0
property aWebView : missing value
property aLog : missing value
property tmpURL : ""

tell current application
  set mePath to ((path to me) as string) & "Contents:Resources:World_map_-_low_resolution.svg"
  
set svgCon to read (mePath as alias)
  
  
set aWidth to 950
  
set aHeight to 650
  
  
  
set paramObj to {myMessage:"Browse World map", mySubMessage:"This is a sample SVG World map", targContents:svgCon, myWidth:(aWidth), myHeight:(aHeight)}
  
–my browseLocalWebContents:paramObj
  
my performSelectorOnMainThread:"browseLocalWebContents:" withObject:(paramObj) waitUntilDone:true
  
return aLog
end tell

on browseLocalWebContents:paramObj
  set aMainMes to (myMessage of paramObj) as string
  
set aSubMes to (mySubMessage of paramObj) as string
  
set tmpURL to (targContents of paramObj) as string –local contents
  
set aWidth to (myWidth of paramObj) as integer
  
set aHeight to (myHeight of paramObj) as integer
  
  
  
set aView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
–Ppopup Buttonをつくる
  
set a1Button to current application’s NSPopUpButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aHeight – 26, 200, 24)) pullsDown:(false)
  
a1Button’s removeAllItems()
  
  
–Menuの中身を作る  
  
set aHTML to current application’s HTMLDocument’s documentWithString:(tmpURL)
  
set fList to (aHTML’s nodesMatchingSelector:"path")’s valueForKeyPath:"attributes.id"
  
set fList to fList’s sortedArrayUsingSelector:"compare:"
  
  
a1Button’s addItemWithTitle:"▼Select"
  
  
repeat with i in fList
    (a1Button’s addItemWithTitle:(i as string))
  end repeat
  
  
a1Button’s setTarget:(me)
  
a1Button’s setAction:("mySelector:")
  
a1Button’s setEnabled:(true)
  
  
set aWebView to makeWebViewAndLoadContents(tmpURL, aWidth, aHeight – 40) of me
  
  
aView’s addSubview:a1Button
  
aView’s addSubview:aWebView
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseLocalWebContents:

on doModal:aParam
  set (my returnCode) to (aParam’s runModal()) as number
end doModal:

on viewDidLoad:aNotification
  return true
end viewDidLoad:

–Popup Action Handler
on actionHandler:sender
  set aTitle to title of sender as string
end actionHandler:

on fetchJSSourceString(aURL)
  set jsURL to |NSURL|’s URLWithString:aURL
  
set jsSourceString to NSString’s stringWithContentsOfURL:jsURL encoding:(NSUTF8StringEncoding) |error|:(missing value)
  
return jsSourceString
end fetchJSSourceString

on mySelector:aSender
  set targetCountry to (aSender’s title()) as string
  
  
set aHTML to current application’s HTMLDocument’s documentWithString:(tmpURL as string)
  
  
set eList to (aHTML’s nodesMatchingSelector:"path") as list
  
set fList to (aHTML’s nodesMatchingSelector:"path")’s valueForKeyPath:"attributes.id"
  
  
–Search Target Country
  
set aRes to (fList)’s indexOfObject:(targetCountry)
  
if (aRes = current application’s NSNotFound) or (aRes > 9.99999999E+8) then
    error "Target country not found"
  end if
  
  
set aRes to aRes + 1
  
  
–Rewrite target country’s fill color on SVG
  
set tmpNode to contents of item aRes of (eList)
  (
tmpNode’s setObject:"Red" forKeyedSubscript:"fill") –Change Target Country’s fill color
  
  
set svgCon to (tmpNode’s |document|()’s serializedFragment()) as string –HTMLReaderはこういう処理ができるところが好き
  
  
aWebView’s loadHTMLString:svgCon baseURL:(missing value)
end mySelector:

on makeWebViewAndLoadContents(aContents as string, aWidth as integer, aHeight as integer)
  set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定URLのJavaScriptをFetch
  
set jsSource to my fetchJSSourceString(aContents)
  
set userScript to WKUserScript’s alloc()’s initWithSource:jsSource injectionTime:(WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
  
set userContentController to WKUserContentController’s alloc()’s init()
  
userContentController’s addUserScript:(userScript)
  
aConf’s setUserContentController:userContentController
  
  
set aWebView to WKWebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
aWebView’s setOpaque:false
  
aWebView’s setBackgroundColor:(NSColor’s clearColor())
  
–aWebView’s scrollView()’s setBackgroundColor:(NSColor’s clearColor())
  
  
aWebView’s loadHTMLString:aContents baseURL:(missing value)
  
return aWebView
end makeWebViewAndLoadContents

★Click Here to Open This Script 

(Visited 72 times, 1 visits today)
Posted in dialog geolocation GUI Image SVG | Tagged 10.13savvy 10.14savvy 10.15savvy HTMLDocument NSAlert NSButton NSColor NSImage NSRunningApplication NSScreen NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

choose location script Library

Posted on 9月 8, 2019 by Takaaki Naganoya

位置情報リストを与え、リスト+地図表示していずれかを選択するUser Interfaceを提供するAppleScriptライブラリです。

–> Download choose location.scptd (To ~/Library/Script Libraries/)

リストに入れた所定のラベルを持つレコードを与えると、地図表示して選択できます。

set aPlaceList to {{title:"Ginza", latitude:"35.67229109", longitude:"139.76575278"}....}

のような名称、緯度、経度のセットを与えます。各位置情報については適宜計算してください(自分はYahoo!の住所ジオコーダーサービスを利用しています)。

地図の表示タイプをGUI上から切り替えられますが、AppleScriptのオプション「initial map type」で初期表示地図タイプを指定できます。


▲初期表示タイプ「map」「satellite」「mixture」(左より)

sdefがいまひとつうまく想定どおりに動いていません。位置情報リストのラベルを予約語として動作させたかったのに、そう動いていませんが、とりあえず現状はこんな感じです(^ー^;; あと、Optional=”Yes”を指定しても省略可能表示になっていないのが謎です。いいのか悪いのか、機能自体に影響がないので現状このままですが、、、

AppleScript名:choose loc sample script
— Created 2019-09-08 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use cLoc : script "choose location"

set aPlaceList to {{title:"Ginza", latitude:"35.67229109", longitude:"139.76575278"}, {title:"Shinjuku", latitude:"35.69096528", longitude:"139.70403520"}, {title:"Kyoto", latitude:"35.00394764", longitude:"135.76277689"}, {title:"Shibuya", latitude:"35.66621547", longitude:"139.71090224"}, {title:"Marunouchi", latitude:"35.67982632", longitude:"139.76364660"}, {title:"Omote-sando", latitude:"35.66621547", longitude:"139.71090224"}, {title:"Nagoya-Sakae", latitude:"35.16556738", longitude:"136.90693150"}, {title:"Fukuoka-Tenjin", latitude:"33.58682428", longitude:"130.39764326"}, {title:"Shinsai-bashi", latitude:"34.67225640", longitude:"135.49985757"}}

set cRes to (choose location from aPlaceList main message "Select Apple Retail Store in Japan" sub message "These stores are almost same. All products are same. The most of visitors are waiting people to repair their broken products." with size {900, 500} initial map type map)

★Click Here to Open This Script 

(Visited 62 times, 1 visits today)
Posted in dialog geolocation GUI Script Libraries sdef | Tagged 10.12savvy 10.13savvy 10.14savvy | 1 Comment

display location Script Library

Posted on 8月 25, 2019 by Takaaki Naganoya

指定の緯度・経度情報の場所を4つの異なる表示倍率の地図でダイアログ表示するAppleScriptライブラリ+呼び出しサンプルです。

–> Download display location.scptd (To ~/Library/Script Libraries/)

サンプルScriptでは、指定のIPアドレスの位置情報をipinfo.io上で調べて表示しています。

本ライブラリは、掲載サンプルのように「display multiple map」コマンドを提供するもので、地図.appに頼らずにAppleScriptだけで簡単な地図表示UIを利用できるようにします。

AppleScript名:display location sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/25
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions
use dispLoc : script "display location"

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

set anIP to "193.228.57.200"
set locList to getGeoLocationByIPinfo(anIP) of me

display multiple map main message "侵略場所の表示" sub message "今回の地球侵略の目的地は、地球上の以下の場所になります" with location locList with size {900, 600}

–http://ipinfo.io/developers
on getGeoLocationByIPinfo(myIP)
  set aURL to "http://ipinfo.io/" & myIP
  
set aRes to callRestGETAPIAndParseResults(aURL, 10) of me
  
  
if aRes = missing value then
    error "Network Error"
  end if
  
set aInfo to loc of aRes
  
set aPos to offset of "," in aInfo
  
set aLatitude to text 1 thru (aPos – 1) of aInfo
  
set aLongitude to text (aPos + 1) thru -1 of aInfo
  
  
return {aLatitude, aLongitude}
end getGeoLocationByIPinfo

on callRestGETAPIAndParseResults(reqURLStr as string, timeoutSec as integer)
  set tmpData to (do shell script "curl -X GET \"" & reqURLStr & "\"")
  
set jsonString to NSString’s stringWithString:tmpData
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
if aJsonDict = missing value then return false
  
return (aJsonDict as record)
end callRestGETAPIAndParseResults

★Click Here to Open This Script 

(Visited 44 times, 1 visits today)
Posted in geolocation GUI JSON Network sdef URL | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

アラートダイアログ上にBrowser+Map Viewを表示 v2

Posted on 3月 17, 2019 by Takaaki Naganoya

ダイアログ上に表示したNSBrowserで都道府県→都道府県別データを選択し、選択したデータの位置情報をMap Viewに表示するAppleScriptの改良版です。

初版掲載時のおかしな挙動を減らし、地図種別の切り替えができるようになっています。本掲載リストだけだと動作が完結しないため、ライブラリを含んだスクリプトバンドルをダウンロードして実行してください。下記リストは「参考までに」掲載しているものです。

–> Download whole Script bundle with Library

前バージョンでは、NSBrowser上でデータが存在していない箇所に空白のセルが表示され、クリックするとクラッシュするという状態でした。本バージョンでもたまに出てくるので完全ではないのですが、

 ・予想どおりデータの行数をカウントするハンドラで絞り込みを行うPredicates文の文字列に問題があった
 ・データに半角のシングルクォートが入っていて、これによってデータの絞り込みに問題が出た

という問題を解消しました。前者はこまめにstringにcastし、後者は全角文字に置き換えました。

それでもまだ問題が出るケースがあるので、まだしばらく実際に使いつつ様子見といったところでしょうか。

AppleScript名:アラートダイアログ上にBrowser+Map Viewを表示 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/03/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use scripting additions
use skLib : script "senjoNoKizunaLib"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSBrowser : a reference to current application’s NSBrowser
property MKMapView : a reference to current application’s MKMapView
property NSScrollView : a reference to current application’s NSScrollView
property NSMutableArray : a reference to current application’s NSMutableArray
property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSAlertSecondButtonReturn : a reference to current application’s NSAlertSecondButtonReturn
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property zLevel : 17
property aMaxViewWidth : 1000
property aMaxViewHeight : 500
property theResult : 0
property returnCode : 0
property theDataSource : {}
property aSelection : {}
property aMapView : missing value
property aBrowser : missing value
property skDataList : {}

property prefList : {"北海道", "青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県", "茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県", "新潟県", "富山県", "石川県", "福井県", "山梨県", "長野県", "岐阜県", "静岡県", "愛知県", "三重県", "滋賀県", "京都府", "大阪府", "兵庫県", "奈良県", "和歌山県", "鳥取県", "島根県", "岡山県", "広島県", "山口県", "徳島県", "香川県", "愛媛県", "高知県", "福岡県", "佐賀県", "長崎県", "熊本県", "大分県", "宮崎県", "鹿児島県", "沖縄県"}

if my skDataList = {} then
  set my skDataList to current application’s NSMutableArray’s arrayWithArray:(getSenjoNokizunaGameCenterDataList() of skLib)
end if

set tmpLen to length of (my skDataList as list)

set aSelection to {}

set paramObj to {myMessage:"Choose a Game Center", mySubMessage:("Choose an appropriate Game Center from list (" & tmpLen as string) & ") to play Senjo-no-Kizuna"}

my performSelectorOnMainThread:"chooseItemByBrowser:" withObject:(paramObj) waitUntilDone:true
if (my returnCode as number) = 1001 then error number -128

return my aSelection
–> {loc_id:"QIEXj9er5QSA_Y42-OjPNg", gcName:"THE 3RD PLANET ジャングルパーク鹿児島", latitude:31.5703088, longitude:130.5653137, address:"鹿児島県 鹿児島市 与次郎 1-11-1 フレスポジャングルパーク2F"}

on chooseItemByBrowser:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
  
— create a view
  
set theView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aMaxViewWidth, aMaxViewHeight))
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(410, 30, aMaxViewWidth – 410, aMaxViewHeight – 30))
  
tell aMapView
    its setMapType:(MKMapTypeStandard)
    
its setZoomEnabled:true
    
its setScrollEnabled:true
    
its setPitchEnabled:true
    
its setRotateEnabled:true
    
its setShowsCompass:true
    
its setShowsZoomControls:true
    
its setShowsScale:true
    
its setShowsUserLocation:true
    
its setDelegate:me
  end tell
  
  
— make browser view with scroll view
  
set aScrollWithTable to makeBrowserView(prefList, 400, aMaxViewHeight) of me
  
  
–Segmented Controlをつくる
  
set segTitleList to {"Map", "Satellite", "Satellite + Map"}
  
set aSeg to makeSegmentedControl(segTitleList, 410, 0, 150, 20) of me
  
  
–Compose Views in NSView
  
theView’s setSubviews:{aScrollWithTable, aMapView, aSeg}
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
end chooseItemByBrowser:

on doModal:aParam
  set (my returnCode) to aParam’s runModal()
end doModal:

on makeBrowserView(aList as list, aWidth as number, aHeight as number)
  set (my theDataSource) to NSMutableArray’s arrayWithArray:aList
  
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aBrowser to NSBrowser’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
aBrowser’s setDelegate:(me)
  
aBrowser’s setTarget:(me)
  
aBrowser’s setAction:"browserCellSelected:"
  
aBrowser’s setMinColumnWidth:120
  
aBrowser’s setSeparatesColumns:true
  
aBrowser’s setMaxVisibleColumns:2
  
aBrowser’s setAutohidesScroller:true
  
aBrowser’s setTakesTitleFromPreviousColumn:true
  
–aBrowser’s setBackgroundColor:(NSColor’s grayColor())
  
  
aScroll’s setDocumentView:aBrowser
  
aBrowser’s enclosingScrollView()’s setHasHorizontalScroller:true
  
aBrowser’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
return aScroll
end makeBrowserView

–NSBrowser Event Handlers
on browser:aView numberOfRowsInColumn:aColumn
  if aColumn = 0 then
    return my theDataSource’s |count|()
  else if aColumn = 1 then
    set aPath to (text 2 thru -1 of ((aView’s |path|()) as string)) as string –ここが問題だったもよう
    
set tmpArray to (my filterRecListByLabel1(skDataList, "address BEGINSWITH ’" & aPath & "’")) as list
    
return (length of tmpArray)
  else
    return 0
  end if
end browser:numberOfRowsInColumn:

on browser:aView willDisplayCell:(aCell) atRow:(rowIndex as integer) column:(colIndex as integer)
  if colIndex = 0 then
    –Prefectures
    
aCell’s setTitle:((item (rowIndex + 1) of prefList) as string)
    
aCell’s setLeaf:false
    
  else if colIndex = 1 then
    –Each Game Centers in the Prefecture
    
set aPath to text 2 thru -1 of ((aView’s |path|()) as string)
    
set tmpArray to my filterRecListByLabel1(skDataList, "address BEGINSWITH ’" & aPath & "’")
    
set tmpItem to (tmpArray’s objectAtIndex:rowIndex)
    
    
set aGameCenterName to (tmpItem’s gcName) as string
    
aCell’s setTitle:(aGameCenterName)
    
aCell’s setLeaf:true
    
  else if colIndex ≥ 2 then
    error "Wrong NSBrowser status"
  end if
end browser:willDisplayCell:atRow:column:

on browserCellSelected:aSender
  set aPath to my aBrowser’s |path|()
  
set aList to (aPath’s pathComponents()) as list
  
set aLen to length of aList
  
  
if aLen = 3 then
    –set aPref to contents of item 2 of aList
    
set aGc to contents of last item of aList
    
    
set tmpArray to my filterRecListByLabel1(skDataList, "gcName == ’" & aGc & "’")
    
–set tmpArray to my filterRecListByLabel1(skDataList, "gcName == " & aGc)
    
set tmpItem to contents of first item of (tmpArray as list)
    
    
copy tmpItem to my aSelection
    
    
set aLatitude to (latitude of tmpItem) as real
    
set aLongitude to (longitude of tmpItem) as real
    
    
tell aMapView
      set aLocation to current application’s CLLocationCoordinate2DMake(aLatitude, aLongitude)
      
its setCenterCoordinate:aLocation zoomLevel:(zLevel) animated:false
    end tell
    
  end if
end browserCellSelected:

–NSArrayに入れたNSDictionaryを、指定の属性ラベルの値で抽出
on filterRecListByLabel1(aRecList, aPredicate as string)
  set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aRecList’s filteredArrayUsingPredicate:aPredicate
  
return filteredArray
end filterRecListByLabel1

–Segmented Controlをつくる
on makeSegmentedControl(titleList, startX, startY, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(startX, startY, aWidth, aHeight))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

–Segmented Controlのクリック時のイベントハンドラ
on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set tList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set tmpType to contents of item (aSel + 1) of tList
  
  
aMapView’s setMapType:(tmpType)
  
  
set selSeg to aSel
end clickedSeg:

★Click Here to Open This Script 

(Visited 53 times, 1 visits today)
Posted in geolocation GUI list Map regexp | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy MKMapTypeHybrid MKMapTypeSatellite MKMapTypeStandard MKMapView NSAlert NSAlertSecondButtonReturn NSBrowser NSColor NSMutableArray NSRunningApplication NSScrollView NSSegmentedControl NSSegmentStyleTexturedRounded NSView | Leave a comment

アラートダイアログ上にBrowser+Map Viewを表示

Posted on 3月 12, 2019 by Takaaki Naganoya

ダイアログ上に表示したNSBrowserで都道府県→都道府県別データを選択し、選択したデータの位置情報をMap Viewに表示するAppleScriptです。

# 2021年11月末にアーケードゲーム「戦場の絆」のサービスが終了したため、Webサイト側からデータ取得する部分の処理は動作しません(Webサイトごとアクセスできなくなったため)


▲macOS 10.12.6上で動作

「OK」ボタンをクリックすると選択したゲームセンターの諸元情報を返してきます。リスト一覧から名称を選択し、途中でその位置情報を地図で見られるという程度のインタフェースです。

NSBrowserを利用したUIの習作で、Web上の「戦場の絆」公式ページから導入店舗の情報を取得し(このあたりライブラリにまとめて部品化)、データを都道府県別にしぼりこんでNSBrowser上で選択できるようにしてみました。


▲macOS 10.13.6上で動作


▲macOS 10.14.4上で動作(Light Mode)


▲macOS 10.14.4上で動作(Dark Mode)

ぱっと見は「何かすごいもの」に見えるのですが、キーワード検索が実装されていないため、データしぼりこみに柔軟性がないと感じるものです。

NSBrowserをAppleScriptから利用した場合に、Xcodeを利用しないとこのレベルの単純なデータ階層固定でデータしぼりこみを行う程度のものしか作りにくいところでしょうか。不可能とは言わないものの、「普通にXcode上で作れば?」という話になると思います。

さらに、該当するカラムの行数を返すハンドラでデータをしぼりこんでレコード数を返しているものの、いまひとつここがうまく動いていない印象を受けます。NSBrowser上で「存在しないデータのような何か」をクリックできるケースがあり、それをクリックすると実行環境(スクリプトエディタとか、Script Debuggerとか)ごとクラッシュします。

→ 原因がわかりました。問題箇所も想像どおり。目下、修正版で謎のゴースト行も出てこなくなったので、あとで修正版を掲載しておきます。問題が2つあって、1つがPredicates文をas stringですべてcastしていなかった件、もうひとつは、、、副次的に発生した問題で、愛知県のデータに「M’s」という半角クォート文字を含むものがあって、これでPredicates文が中断されてしまった問題。半角シングルクォートを全角に置き換えるとかいろいろ手を加える必要がありました。

本Script全体をダウンロードして、スクリプトエディタ上で実行すると、最初に「戦場の絆」公式ホームページの日本国内の店舗情報をスキャンして店舗情報を抽出するため、サーバーの混雑具合やネットワーク回線速度にも左右されますが、自分の環境では5〜15秒程度でデータの取得が終了し、ダイアログが表示されます。

–> Download whole Script bundle with Library

AppleScript名:アラートダイアログ上にBrowser+Map Viewを表示.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/03/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use scripting additions
use skLib : script "senjoNoKizunaLib"

property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSBrowser : a reference to current application’s NSBrowser
property MKMapView : a reference to current application’s MKMapView
property NSScrollView : a reference to current application’s NSScrollView
property NSMutableArray : a reference to current application’s NSMutableArray
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSAlertSecondButtonReturn : a reference to current application’s NSAlertSecondButtonReturn

property zLevel : 17
property aMaxViewWidth : 1000
property aMaxViewHeight : 500
property theResult : 0
property returnCode : 0
property theDataSource : {}
property aSelection : {}
property aMapView : missing value
property aBrowser : missing value
property skDataList : {}

property prefList : {"北海道", "青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県", "茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県", "新潟県", "富山県", "石川県", "福井県", "山梨県", "長野県", "岐阜県", "静岡県", "愛知県", "三重県", "滋賀県", "京都府", "大阪府", "兵庫県", "奈良県", "和歌山県", "鳥取県", "島根県", "岡山県", "広島県", "山口県", "徳島県", "香川県", "愛媛県", "高知県", "福岡県", "佐賀県", "長崎県", "熊本県", "大分県", "宮崎県", "鹿児島県", "沖縄県"}

if my skDataList = {} then
  set my skDataList to current application’s NSMutableArray’s arrayWithArray:(getSenjoNokizunaGameCenterDataList() of skLib)
end if

set aSelection to {}

set paramObj to {myMessage:"Choose a Game Center", mySubMessage:"Choose an appropriate Game Center from list to play Senjo-no-Kizuna"}

my performSelectorOnMainThread:"chooseItemByBrowser:" withObject:(paramObj) waitUntilDone:true
return my aSelection
–> {loc_id:"QIEXj9er5QSA_Y42-OjPNg", gcName:"THE 3RD PLANET ジャングルパーク鹿児島", latitude:31.5703088, longitude:130.5653137, address:"鹿児島県 鹿児島市 与次郎 1-11-1 フレスポジャングルパーク2F"}

on chooseItemByBrowser:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
  
— create a view
  
set theView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aMaxViewWidth, aMaxViewHeight))
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(410, 0, aMaxViewWidth – 410, aMaxViewHeight))
  
tell aMapView
    its setMapType:(MKMapTypeStandard)
    
its setZoomEnabled:true
    
its setScrollEnabled:true
    
its setPitchEnabled:true
    
its setRotateEnabled:true
    
its setShowsCompass:true
    
its setShowsZoomControls:true
    
its setShowsScale:true
    
its setShowsUserLocation:true
    
its setDelegate:me
  end tell
  
  
— make browser view with scroll view
  
set aScrollWithTable to makeBrowserView(prefList, 400, aMaxViewHeight) of me
  
  
–Compose Views in NSView
  
theView’s setSubviews:{aScrollWithTable, aMapView}
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
end chooseItemByBrowser:

on doModal:aParam
  set (my returnCode) to aParam’s runModal()
end doModal:

on makeBrowserView(aList as list, aWidth as number, aHeight as number)
  set (my theDataSource) to NSMutableArray’s arrayWithArray:aList
  
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aBrowser to NSBrowser’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
aBrowser’s setDelegate:(me)
  
aBrowser’s setTarget:(me)
  
aBrowser’s setAction:"browserCellSelected:"
  
aBrowser’s setMinColumnWidth:120
  
aBrowser’s setSeparatesColumns:true
  
aBrowser’s setMaxVisibleColumns:2
  
aBrowser’s setAutohidesScroller:true
  
aBrowser’s setTakesTitleFromPreviousColumn:true
  
–aBrowser’s setBackgroundColor:(NSColor’s grayColor())
  
  
aScroll’s setDocumentView:aBrowser
  
aBrowser’s enclosingScrollView()’s setHasHorizontalScroller:true
  
aBrowser’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
return aScroll
end makeBrowserView

–NSBrowser Event Handlers
–ここ、いまひとつきちんと動いていないかも???
on browser:aView numberOfRowsInColumn:aColumn
  if aColumn = 0 then
    return my theDataSource’s |count|()
  else if aColumn = 1 then
    set aPath to text 2 thru -1 of ((aView’s |path|()) as string)
    
set tmpArray to (my filterRecListByLabel1(skDataList, "address BEGINSWITH ’" & aPath & "’")) as list
    
return (length of tmpArray)
  end if
end browser:numberOfRowsInColumn:

on browser:aView willDisplayCell:(aCell) atRow:(rowIndex as integer) column:(colIndex as integer)
  if colIndex = 0 then
    –Prefectures
    
aCell’s setTitle:((item (rowIndex + 1) of prefList) as string)
    
aCell’s setLeaf:false
    
  else if colIndex = 1 then
    –Each Game Centers in the Prefecture
    
set aPath to text 2 thru -1 of ((aView’s |path|()) as string)
    
set tmpArray to my filterRecListByLabel1(skDataList, "address BEGINSWITH ’" & aPath & "’")
    
set tmpItem to (tmpArray’s objectAtIndex:rowIndex)
    
    
set aGameCenterName to (tmpItem’s gcName) as string
    
aCell’s setTitle:(aGameCenterName)
    
aCell’s setLeaf:true
    
  end if
end browser:willDisplayCell:atRow:column:

on browserCellSelected:aSender
  set aPath to my aBrowser’s |path|()
  
set aList to (aPath’s pathComponents()) as list
  
set aLen to length of aList
  
  
if aLen = 3 then
    –set aPref to contents of item 2 of aList
    
set aGc to contents of last item of aList
    
    
set tmpArray to my filterRecListByLabel1(skDataList, "gcName == ’" & aGc & "’")
    
set tmpItem to contents of first item of (tmpArray as list)
    
    
copy tmpItem to my aSelection
    
    
set aLatitude to (latitude of tmpItem) as real
    
set aLongitude to (longitude of tmpItem) as real
    
    
tell aMapView
      set aLocation to current application’s CLLocationCoordinate2DMake(aLatitude, aLongitude)
      
its setCenterCoordinate:aLocation zoomLevel:(zLevel) animated:false
    end tell
    
  end if
end browserCellSelected:

–NSArrayに入れたNSDictionaryを、指定の属性ラベルの値で抽出
on filterRecListByLabel1(aRecList, aPredicate as string)
  set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aRecList’s filteredArrayUsingPredicate:aPredicate
  
return filteredArray
end filterRecListByLabel1

★Click Here to Open This Script 

(Visited 59 times, 1 visits today)
Posted in geolocation list Record | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy MKMapTypeStandard MKMapView NSAlert NSAlertSecondButtonReturn NSBrowser NSColor NSMutableArray NSRunningApplication NSScrollView NSView | Leave a comment

アラートダイアログ上に複数のNSBoxを作成してMKMapViewを表示

Posted on 3月 11, 2019 by Takaaki Naganoya

指定されたIPアドレスの位置情報(geo location)を検索して、アラートダイアログ上に拡大レベルの異なる4つの地図を表示するAppleScriptです。

IP Goecodingのサービスはipinfo.ioを利用しています。ただ、この手のサービスは入れ替わりが激しいので、長期的に使い続けられることを期待できないと感じています(有償サービスは別)。

このズームレベルが異なる地図の同時表示Viewは、作成したときには「これは画期的!」「ものすごく使いやすい!」と、狂喜乱舞したものですが、他のユーザーに見せてデモしたら、

「実際には限定されたエリア内の位置データを見ることが多いので、World LevelとかCountry Levelのビューは無駄なことが多い」
「地球を侵略しに来た異星人には向いているが、地球人向けには冗長」

といった意見が多く、オクラ入りしていました。アラートダイアログでさまざまなデータを可視化する部品の整備計画時に倉庫から引っ張り出されてきたものです。

唯一、IPアドレスという「見ただけではどこの国のものだかわからない」(Class AのIPは別。17.のAppleとか)データを可視化するときにはバッチリ合っています。

macOS 10.12〜10.14で確認していますが、唯一、macOS 10.14.4上では初期状態でピンが表示されません。ピン自体は存在しているので、地図表示タイプを変更すると表示されるのですが、一体これはどうしたものか。仕様なのかバグなのかわかりません。


▲なぜか本Blogにロス市警からのアクセスが(汗)


▲macOS 10.12.6 Map


▲macOS 10.12.6 Satellite


▲macOS 10.12.6 Map + Satellite


▲macOS 10.13.6 Map


▲macOS 10.14.4 Map (Light Mode)


▲macOS 10.14.4 Map (Dark Mode)

AppleScript名:アラートダイアログ上に複数のNSBoxを作成してMKMapViewを表示
— Created 2019-03-11 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use framework "CoreLocation"

property NSAlert : a reference to current application’s NSAlert
property NSString : a reference to current application’s NSString
property NSScreen : a reference to current application’s NSScreen
property MKMapView : a reference to current application’s MKMapView
property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKPointAnnotation : a reference to current application’s MKPointAnnotation
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property windisp : false
property selSeg : 0
property aMapViewList : {}

property segTitleList : {"Map", "Satellite", "Satellite + Map"}

property returnCode : 0

set aClip to the clipboard –このへんてきとう
set anIP to text returned of (display dialog "Input IP address to find its location" default answer aClip)

set windisp to false
set geoInfo to getGeoLocationByIPinfo(anIP) of me
if geoInfo = missing value then
  error "Network Error"
end if

set aInfo to loc of geoInfo

set aPos to offset of "," in aInfo
set aLatitude to text 1 thru (aPos – 1) of aInfo
set aLongitude to text (aPos + 1) thru -1 of aInfo

set aWidth to 1000
set aHeight to 600

set aButtonMSG to "OK"
set aMapViewList to {}

set paramObj to {viewWidth:aWidth, viewHeight:aHeight, viewTitle:anIP, viewSubTitle:"IP-Geocoding Service by ipinfo.io", viewLat:aLatitude, viewLong:aLongitude}

my performSelectorOnMainThread:"dispMapViewinDifferentScales:" withObject:(paramObj) waitUntilDone:true

on dispMapViewinDifferentScales:paramObj
  set aWidth to (viewWidth of paramObj) as real
  
set aHeight to (viewHeight of paramObj) as real
  
set aLat to (viewLat of paramObj) as real
  
set aLong to (viewLong of paramObj) as real
  
set aTitle to (viewTitle of paramObj) as string
  
set aSubTitle to (viewSubTitle of paramObj) as string
  
  
set selSeg to 0
  
  
–NSViewをつくる
  
set aView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
  
–各レベルのMapViewをBoxでつくる
  
set wList to {{3, "🌏World Level Map"}, {5, "🏰Country Level Map"}, {10, "🏢City Level Map"}, {17, "🏠Town Level Map"}}
  
set xPos to 0
  
repeat with i in wList
    copy i to {aLevelNum, aBoxTitle}
    
    
–Boxをつくる
    
set aBox to (current application’s NSBox’s alloc()’s initWithFrame:(current application’s NSMakeRect(xPos, 40, aWidth * 0.25, aHeight – 70)))
    (
aBox’s setTitle:aBoxTitle)
    
    
–MapView+Pinをつくる
    
set aMapView to makeMKMapView(aWidth * 0.25, aHeight – 70, aLevelNum, aLat, aLong, aTitle) of me
    
    (
aBox’s addSubview:aMapView)
    (
aView’s addSubview:aBox)
    
    
set the end of aMapViewList to aMapView
    
set xPos to xPos + (aWidth * 0.25)
  end repeat
  
  
–Segmented Controlをつくる
  
set aSeg to makeSegmentedControl(segTitleList, aWidth, aHeight) of me
  
aView’s addSubview:aSeg
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aTitle
    
its setInformativeText:aSubTitle
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
end dispMapViewinDifferentScales:

on doModal:aParam
  set (my returnCode) to aParam’s runModal()
end doModal:

–MKMapViewをつくる
on makeMKMapView(aWidth, aHeight, aZoomLevel, aLat, aLong, aTitle)
  set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aMapView’s setMapType:(current application’s MKMapTypeStandard)
  
  
aMapView’s setZoomEnabled:true
  
aMapView’s setScrollEnabled:true
  
aMapView’s setPitchEnabled:false
  
aMapView’s setRotateEnabled:false
  
aMapView’s setShowsCompass:true
  
aMapView’s setShowsZoomControls:true
  
aMapView’s setShowsScale:true
  
aMapView’s setShowsUserLocation:true
  
  
set aLocation to current application’s CLLocationCoordinate2DMake(aLat, aLong)
  
aMapView’s setCenterCoordinate:aLocation zoomLevel:aZoomLevel animated:false
  
aMapView’s setDelegate:me
  
  
–MapにPinを追加
  
set anAnnotation to current application’s MKPointAnnotation’s alloc()’s init()
  
anAnnotation’s setCoordinate:aLocation
  
anAnnotation’s setTitle:aTitle
  
aMapView’s addAnnotation:anAnnotation
  
  
return aMapView
end makeMKMapView

–Make Segmented Control
on makeSegmentedControl(titleList, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(10, 5, 260, 30))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

–Segmented Control’s clicked event handler
on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set selSeg to (aSel + 1)
  
set mapList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set curMap to contents of item selSeg of mapList
  
  
repeat with i in aMapViewList
    set aView to contents of i
    (
aView’s setMapType:(curMap))
  end repeat
end clickedSeg:

–http://ipinfo.io/developers
on getGeoLocationByIPinfo(myIP)
  set aURL to "http://ipinfo.io/" & myIP
  
set aRes to callRestGETAPIAndParseResults(aURL, 10) of me
  
return aRes as record
end getGeoLocationByIPinfo

on callRestGETAPIAndParseResults(reqURLStr as string, timeoutSec as integer)
  set tmpData to (do shell script "curl -X GET \"" & reqURLStr & "\"")
  
set jsonString to NSString’s stringWithString:tmpData
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
if aJsonDict = missing value then return false
  
return (aJsonDict as record)
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to NSMutableDictionary’s dictionaryWithDictionary:aRec
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

★Click Here to Open This Script 

(Visited 40 times, 1 visits today)
Posted in geolocation Network REST API | Tagged 10.11savvy 10.12savvy MKMapTypeHybrid MKMapTypeSatellite MKMapTypeStandard MKMapView MKPointAnnotation NSAlert NSJSONSerialization NSRunningApplication NSScreen NSSegmentedControl NSSegmentStyleTexturedRounded NSString NSUTF8StringEncoding | Leave a comment

アラートダイアログ上にTable View+Map View+Segmented Controlを表示

Posted on 2月 23, 2019 by Takaaki Naganoya

アラートダイアログを作成し、その上にScroll View+Table ViewおよびMap Viewを表示して選択肢の選択を行うAppleScriptです。Segmented Controlで地図の種別切り替えを行い、項目選択用のTable Viewを編集不可にしました。

Map Viewを使用するために、インターネット接続が必要です。地図表示パフォーマンスはインターネット接続速度次第です。


▲Map Type = Standard (Map)


▲Map Type = Satellite


▲Map Type = Hybrid (Satellite + Map)

本Scriptに与える緯度・経度情報についてはあらかじめ住所ジオコーダーによって「住所情報→緯度・経度情報」の変換を行なったものを書いておく必要がありますが、Yahoo!の住所ジオコーダーサービスなどを呼び出せば、住所情報をパラメーターとすることも可能です。

サンプルデータの緯度・経度情報は、例によって「戦場の絆」の入っている近所のゲーセンの情報を適当にみつくろって入れてみたものです。

本ダイアログは、それほど件数の多くない(20件ぐらい?)選択肢からの選択を意図して作ったものですが、数百件とか数千件のデータから選ぶような場合には、Outline Viewを利用して小エリアごとに分割するとか、Search Fieldを連動させてキーワードによる絞り込みを有効にするなど、それなりの対処が必要です。

AppleScript名:アラートダイアログ上にTable View+Map View+Segmented Controlを表示
— Created 2019-02-23 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"

property NSAlert : a reference to current application’s NSAlert
property NSIndexSet : a reference to current application’s NSIndexSet
property MKMapView : a reference to current application’s MKMapView
property NSScrollView : a reference to current application’s NSScrollView
property NSTableView : a reference to current application’s NSTableView
property NSTableColumn : a reference to current application’s NSTableColumn
property NSMutableArray : a reference to current application’s NSMutableArray
property MKPointAnnotation : a reference to current application’s MKPointAnnotation
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSAlertSecondButtonReturn : a reference to current application’s NSAlertSecondButtonReturn
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard

property zLevel : 21 –Map Zoom Level (0:World View, 21:House/Building Zoom View)
property aMaxViewWidth : 800
property theResult : 0
property returnCode : 0
property theDataSource : {}
property curRow : 0
property aMapView : missing value
property nameL : {}
property placeL : {}

set aPlaceList to {{placeName:"Hey", aLat:"35.69906613", aLong:"139.77084064"}, {placeName:"namco中野", aLat:"35.70859274", aLong:"139.66584339"}, {placeName:"ゲームシティ板橋", aLat:"35.74572771", aLong:"139.67553260"}, {placeName:"ラウンドワンスタジアム板橋", aLat:"35.77661583", aLong:"139.67864491"}, {placeName:"キャロム練馬", aLat:"35.76386421", aLong:"139.66591600"}, {placeName:"アミュージアムOSC", aLat:"35.75308308", aLong:"139.59476696"}}

set paramObj to {myMessage:"場所の選択", mySubMessage:"適切な場所を以下のリストからえらんでください", placeList:aPlaceList}
my performSelectorOnMainThread:"chooseItemByTableViewWithMapAndSegment:" withObject:(paramObj) waitUntilDone:true
if (my theResult) = 0 then error number -128
return (my theResult)

on chooseItemByTableViewWithMapAndSegment:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set aTList to (placeList of paramObj) as list
  
  
set nameL to {}
  
set placeL to {}
  
repeat with i in aTList
    set the end of nameL to (placeName of i)
    
set the end of placeL to {contents of (aLat of i), contents of (aLong of i)}
  end repeat
  
  
— create a view
  
set theView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aMaxViewWidth, 400))
  
  
— make table view with scroll view
  
set aScrollWithTable to makeTableView(nameL, 200, 400) of me
  
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(210, 30, aMaxViewWidth – 210, 370))
  
tell aMapView
    its setMapType:MKMapTypeStandard
    
its setZoomEnabled:true
    
its setScrollEnabled:true
    
its setPitchEnabled:true
    
its setRotateEnabled:true
    
its setShowsCompass:true
    
its setShowsZoomControls:true
    
its setShowsScale:true
    
its setShowsUserLocation:true
    
    
set aLocation to current application’s CLLocationCoordinate2DMake((first item of first item of placeL) as real, (second item of first item of placeL) as real)
    
its setCenterCoordinate:aLocation zoomLevel:(zLevel) animated:false
    
its setDelegate:me
  end tell
  
  
–MapにPinを追加
  
repeat with i from 1 to (length of nameL)
    set tmpAdr to contents of item i of nameL
    
copy item i of placeL to {tmpLat, tmpLong}
    
    
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat as real, tmpLong as real)
    
set anAnnotation to MKPointAnnotation’s alloc()’s init()
    (
anAnnotation’s setCoordinate:aLocation)
    (
anAnnotation’s setTitle:tmpAdr)
    (
aMapView’s addAnnotation:anAnnotation)
  end repeat
  
  
–Segmented Controlをつくる
  
set segTitleList to {"Map", "Satellite", "Satellite + Map"}
  
set aSeg to makeSegmentedControl(segTitleList, 210, 0, 150, 20) of me
  
  
theView’s setSubviews:{aScrollWithTable, aMapView, aSeg}
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
  end tell
  
  
–To enable the first annotation visible
  
copy item 1 of placeL to {tmpLat, tmpLong}
  
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat as real, tmpLong as real)
  
aMapView’s setCenterCoordinate:aLocation zoomLevel:(zLevel) animated:false
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
set (my theResult) to (aScrollWithTable’s documentView’s selectedRow()) + 1
end chooseItemByTableViewWithMapAndSegment:

on doModal:aParam
  set (my returnCode) to aParam’s runModal()
end doModal:

on makeTableView(aList as list, aWidth as number, aHeight as number)
  set aOffset to 0
  
  
set sourceList to {}
  
repeat with i in aList
    set the end of sourceList to {dataItem:(contents of i)}
  end repeat
  
  
set theDataSource to NSMutableArray’s alloc()’s init()
  
theDataSource’s addObjectsFromArray:sourceList
  
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 30, aWidth, aHeight – 30))
  
set aView to NSTableView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 30, aWidth, aHeight – 30))
  
  
  
set aColumn to (NSTableColumn’s alloc()’s initWithIdentifier:"dataItem")
  (
aColumn’s setWidth:aWidth)
  (
aColumn’s headerCell()’s setStringValue:"dataItem")
  (
aView’s addTableColumn:aColumn)
  
  
aView’s setDelegate:me
  
aView’s setDataSource:me
  
aView’s reloadData()
  
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
–1行目を選択
  
set aIndexSet to NSIndexSet’s indexSetWithIndex:0
  
aView’s selectRowIndexes:aIndexSet byExtendingSelection:false
  
  
–強制的にトップにスクロール
  
set aDBounds to aScroll’s documentView()’s |bounds|()
  
if class of aDBounds = list then
    –macOS 10.13 or later
    
set maxHeight to item 2 of item 1 of aDBounds
  else
    –macOS 10.10, 10.11, 10.12
    
set maxHeight to height of |size| of aDBounds
  end if
  
  
set aPT to current application’s NSMakePoint(0.0, -40.0) —— (aScroll’s documentView()’s |bounds|()’s |size|()’s height))
  
aScroll’s documentView()’s scrollPoint:aPT
  
  
return aScroll
end makeTableView

–TableView Event Handlers
on numberOfRowsInTableView:aView
  return my theDataSource’s |count|()
end numberOfRowsInTableView:

on tableView:aView objectValueForTableColumn:aColumn row:aRow
  set (tmpRow) to aView’s selectedRow() as number
  
  
–Table View上で現在選択行「以外の」行が選択されたら、Mapを選択項目で更新
  
if (my curRow) is not equal to tmpRow then
    set tmpLat to (first item of item (tmpRow + 1) of placeL) as real
    
set tmpLong to (second item of item (tmpRow + 1) of placeL) as real
    
    
tell aMapView
      set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
      
its setCenterCoordinate:aLocation zoomLevel:(zLevel) animated:false
    end tell
    
    
set (my curRow) to tmpRow
  end if
  
  
set aRec to (my theDataSource)’s objectAtIndex:(aRow as number)
  
set aTitle to (aColumn’s headerCell()’s title()) as string
  
set aRes to (aRec’s valueForKey:aTitle)
  
return aRes
end tableView:objectValueForTableColumn:row:

on tableView:aView shouldEditTableColumn:aTableColumn row:rowIndex
  return false –Not Editable
end tableView:shouldEditTableColumn:row:

–Segmented Controlをつくる
on makeSegmentedControl(titleList, startX, startY, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(startX, startY, aWidth, aHeight))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

–Segmented Controlのクリック時のイベントハンドラ
on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set tList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set tmpType to contents of item (aSel + 1) of tList
  
  
aMapView’s setMapType:(tmpType)
  
  
set selSeg to aSel
end clickedSeg:

★Click Here to Open This Script 

(Visited 44 times, 1 visits today)
Posted in geolocation GUI | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy MKMapView MKPointAnnotation NSAlert NSAlertSecondButtonReturn NSIndexSet NSMutableArray NSRunningApplication NSScrollView NSSegmentedControl NSSegmentStyleTexturedRounded NSTableColumn NSTableView | Leave a comment

アラートダイアログ上にTable View+Map Viewを表示

Posted on 2月 22, 2019 by Takaaki Naganoya

アラートダイアログを作成し、その上にScroll View+Table ViewおよびMap Viewを表示して選択肢の選択を行うAppleScriptです。

Map Viewを使用するために、インターネット接続が必要です。地図表示パフォーマンスはインターネット接続速度次第です。

{{placeName:"Hey", aLat:"35.69906613", aLong:"139.77084064"}....}

のように位置データを、

名称, 緯度, 経度

とまとめたリストで選択肢を指定します。実行すると選択肢のアイテム番号(1からはじまる)を返してきます。


▲左から、macOS 10.12.6、10.13.6、10.14.4betaで同じAppleScriptを動かしたところ。同じ場所、同じZoom LevelでもOSバージョンごとに微妙に表示内容が違う

現状の実装では、表UI(Table View)内のデータがダブルクリックで編集できてしまうので、編集できないようにするあたりが改良対象でしょうか。あと、地図・衛星写真の切り替えもつけておくとよいでしょう。

本Scriptに与える緯度・経度情報についてはあらかじめ住所ジオコーダーによって「住所情報→緯度・経度情報」の変換を行なったものを書いておく必要がありますが、Yahoo!の住所ジオコーダーサービスなどを呼び出せば、住所情報をパラメーターとすることも可能です。

サンプルデータの緯度・経度情報は、例によって「戦場の絆」の入っている近所のゲーセンの情報を適当にみつくろって入れてみたものです。

AppleScript名:アラートダイアログ上にTable View+Map Viewを表示 v2
— Created 2019-02-22 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"

property NSAlert : a reference to current application’s NSAlert
property NSIndexSet : a reference to current application’s NSIndexSet
property MKMapView : a reference to current application’s MKMapView
property NSScrollView : a reference to current application’s NSScrollView
property NSTableView : a reference to current application’s NSTableView
property NSTableColumn : a reference to current application’s NSTableColumn
property NSMutableArray : a reference to current application’s NSMutableArray
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSAlertSecondButtonReturn : a reference to current application’s NSAlertSecondButtonReturn

property zLevel : 18
property aMaxViewWidth : 800
property theResult : 0
property returnCode : 0
property theDataSource : {}
property curRow : 0
property aMapView : missing value
property nameL : {}
property placeL : {}

set aPlaceList to {{placeName:"Hey", aLat:"35.69906613", aLong:"139.77084064"}, {placeName:"namco中野", aLat:"35.70859274", aLong:"139.66584339"}, {placeName:"ゲームシティ板橋", aLat:"35.74572771", aLong:"139.67553260"}, {placeName:"ラウンドワンスタジアム板橋", aLat:"35.77661583", aLong:"139.67864491"}, {placeName:"キャロム練馬", aLat:"35.76386421", aLong:"139.66591600"}, {placeName:"アミュージアムOSC", aLat:"35.75308308", aLong:"139.59476696"}}

set paramObj to {myMessage:"場所の選択", mySubMessage:"適切な場所を以下のリストからえらんでください", placeList:aPlaceList}
my performSelectorOnMainThread:"chooseItemByTableViewWithMap:" withObject:(paramObj) waitUntilDone:true
return (my theResult)

on chooseItemByTableViewWithMap:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set aTList to (placeList of paramObj) as list
  
  
set nameL to {}
  
set placeL to {}
  
repeat with i in aTList
    set the end of nameL to (placeName of i)
    
set the end of placeL to {contents of (aLat of i), contents of (aLong of i)}
  end repeat
  
  
— create a view
  
set theView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aMaxViewWidth, 400))
  
  
— make table view with scroll view
  
set aScrollWithTable to makeTableView(nameL, 200, 400) of me
  
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(210, 0, aMaxViewWidth – 210, 400))
  
tell aMapView
    its setMapType:(current application’s MKMapTypeStandard)
    
its setZoomEnabled:true
    
its setScrollEnabled:true
    
its setPitchEnabled:true
    
its setRotateEnabled:true
    
its setShowsCompass:true
    
its setShowsZoomControls:true
    
its setShowsScale:true
    
its setShowsUserLocation:true
    
    
set aLocation to current application’s CLLocationCoordinate2DMake((first item of first item of placeL) as real, (second item of first item of placeL) as real)
    
    
its setCenterCoordinate:aLocation zoomLevel:(zLevel) animated:false
    
its setDelegate:me
  end tell
  
  
theView’s setSubviews:{aScrollWithTable, aMapView}
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
  
  
set (my theResult) to (aScrollWithTable’s documentView’s selectedRow()) + 1
end chooseItemByTableViewWithMap:

on doModal:aParam
  set (my returnCode) to aParam’s runModal()
end doModal:

on makeTableView(aList as list, aWidth as number, aHeight as number)
  set aOffset to 0
  
  
set sourceList to {}
  
repeat with i in aList
    set the end of sourceList to {dataItem:(contents of i)}
  end repeat
  
  
set theDataSource to NSMutableArray’s alloc()’s init()
  
theDataSource’s addObjectsFromArray:sourceList
  
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aOffset, aWidth, aHeight))
  
set aView to NSTableView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, aOffset, aWidth, aHeight))
  
  
  
set aColumn to (NSTableColumn’s alloc()’s initWithIdentifier:"dataItem")
  (
aColumn’s setWidth:aWidth)
  (
aColumn’s headerCell()’s setStringValue:"dataItem")
  (
aView’s addTableColumn:aColumn)
  
  
aView’s setDelegate:me
  
aView’s setDataSource:me
  
aView’s reloadData()
  
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
–1行目を選択
  
set aIndexSet to NSIndexSet’s indexSetWithIndex:0
  
aView’s selectRowIndexes:aIndexSet byExtendingSelection:false
  
  
–強制的にトップにスクロール
  
–強制的にトップにスクロール
  
–set maxHeight to aScroll’s documentView()’s |bounds|()’s |size|()’s height
  
set aDBounds to aScroll’s documentView()’s |bounds|()
  
if class of aDBounds = list then
    –macOS 10.13 or later
    
set maxHeight to item 2 of item 1 of aDBounds
  else
    –macOS 10.10….10.12
    
set maxHeight to height of |size| of aDBounds
  end if
  
  
set aPT to current application’s NSMakePoint(0.0, -40.0) —— (aScroll’s documentView()’s |bounds|()’s |size|()’s height))
  
aScroll’s documentView()’s scrollPoint:aPT
  
  
return aScroll
end makeTableView

–TableView Event Handlers
on numberOfRowsInTableView:aView
  return my theDataSource’s |count|()
end numberOfRowsInTableView:

on tableView:aView objectValueForTableColumn:aColumn row:aRow
  set (tmpRow) to aView’s selectedRow() as number
  
  
–Table View上で現在選択行「以外の」行が選択されたら、Mapを選択項目で更新
  
if (my curRow) is not equal to tmpRow then
    set tmpLat to (first item of item (tmpRow + 1) of placeL) as real
    
set tmpLong to (second item of item (tmpRow + 1) of placeL) as real
    
    
tell aMapView
      set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
      
its setCenterCoordinate:aLocation zoomLevel:(zLevel) animated:false
    end tell
    
    
set (my curRow) to tmpRow
  end if
  
  
set aRec to (my theDataSource)’s objectAtIndex:(aRow as number)
  
set aTitle to (aColumn’s headerCell()’s title()) as string
  
set aRes to (aRec’s valueForKey:aTitle)
  
return aRes
end tableView:objectValueForTableColumn:row:

★Click Here to Open This Script 

(Visited 68 times, 1 visits today)
Posted in geolocation GUI list | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy MKMapView NSAlert NSAlertSecondButtonReturn NSIndexSet NSMutableArray NSRunningApplication NSScrollView NSTableColumn NSTableView | Leave a comment

アラートダイアログ上にMap Viewを表示

Posted on 2月 19, 2019 by Takaaki Naganoya

アラートダイアログを作成し、その上にMap Viewを表示して位置座標の選択を行うAppleScriptです。

Map Viewを使用するためには、インターネット接続が必要です。

もしこれをAppleScriptのコマンドのように表現するなら「choose geo location」とかいうコマンドになるでしょうか。本当は地図.appのように地図中でクリックした場所にピンを打って選択箇所を明示するようなものを考えていたのですが、実際にASだけで作ろうとすると難しいものがありそうで。

こうした「ざっくり場所を選ぶ」ダイアログのほか、複数の地点をピンで表示し、そのうちのどれかを地図上で選択するといったコマンドがあると使いでがありそうです。

AppleScript名:アラートダイアログ上のMap Viewを表示
— Created 2019-02-14 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "MapKit"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSData : a reference to current application’s NSData
property MKMapView : a reference to current application’s MKMapView
property NSURLRequest : a reference to current application’s NSURLRequest
property NSURLConnection : a reference to current application’s NSURLConnection

property theResult : 0
property returnCode : 0

set nRes to hasInternetConnection("http://www.google.com") of me
if nRes = false then error "No Internet Connection…."

–地図表示初期座標。一般的にはWiFi経由でAssistive-GPSから現在位置を拾って指定
set aLong to 130.55723797
set aLat to 31.57868838

set paramObj to {myMessage:"場所の選択", mySubMessage:"目標の場所を地図中央に入れてください", aLongitude:aLong, aLatitude:aLat}
my performSelectorOnMainThread:"chooseCoordinate:" withObject:(paramObj) waitUntilDone:true
return theResult
–> {latitude:31.57868838, longitude:130.55723797}

on chooseCoordinate:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set aLong to aLongitude of paramObj
  
set aLat to aLatitude of paramObj
  
  
–MKMapViewをつくる
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 500, 300))
  
tell aMapView
    its setMapType:(current application’s MKMapTypeStandard)
    
its setZoomEnabled:true
    
its setScrollEnabled:true
    
its setPitchEnabled:true
    
its setRotateEnabled:true
    
its setShowsCompass:true
    
its setShowsZoomControls:true
    
its setShowsScale:true
    
its setShowsUserLocation:true
    
    
set aLocation to current application’s CLLocationCoordinate2DMake(aLat, aLong)
    
its setCenterCoordinate:aLocation zoomLevel:17 animated:false
    
its setDelegate:me
  end tell
  
  
— set up alert  
  
set theAlert to current application’s NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aMapView
  end tell
  
  
— show alert in modal loop
  
current application’s NSRunningApplication’s currentApplication()’s activateWithOptions:(current application’s NSApplicationActivateIgnoringOtherApps)
  
set returnCode to theAlert’s runModal()
  
if returnCode = (current application’s NSAlertSecondButtonReturn) then error number -128
  
  
set (my theResult) to (aMapView’s centerCoordinate()) as record
end chooseCoordinate:

–Internet Connection Check
on hasInternetConnection(aURLString)
  set aURL to |NSURL|’s alloc()’s initWithString:aURLString
  
set aReq to NSURLRequest’s alloc()’s initWithURL:aURL cachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:5.0
  
set urlRes to (NSURLConnection’s sendSynchronousRequest:aReq returningResponse:(missing value) |error|:(missing value))
  
if urlRes = missing value then
    return false
  else
    return true
  end if
end hasInternetConnection

★Click Here to Open This Script 

(Visited 66 times, 1 visits today)
Posted in geolocation GUI Internet | Tagged 10.11savvy 10.12savvy 10.13savvy NSData NSURL NSView | Leave a comment

Photosで選択中の写真が指定場所から50メートル以内の場合には書き出してFineReader OCR Proで処理 v2.1

Posted on 10月 30, 2018 by Takaaki Naganoya

Photos(写真).app上で選択中の写真が、指定場所から50メートル以内の場合にはファイルに書き出して、OCRアプリケーション「FineReader OCR Pro」でOCR処理するAppleScriptです。

–> Demo Movie

アーケードゲーム「戦場の絆」のリプレイムービーは、プレイ後の操作により1日に2プレイ分までYouTubeにアップロードされる仕様になっています。プレイ後、ゲーセンのターミナル上で操作してリプレイムービーにアクセスするためのアクセスコード(リプレイID)が表示されるようになっています。

この、ターミナル上のアクセスコードをiPhoneで写真撮影すると、写真に撮影場所のGPSデータが添付されます。写真.app経由でこのGPSデータを取得し、指定場所(ゲームセンター)から50メートル以内であればターミナルで撮影した写真と判定。

この写真をファイル書き出しして、OCRアプリケーションで認識しやすいようにCocoaの機能を用いて階調反転。一昔前ならPhotoshopで処理していましたが、いまならAppleScriptだけで高速に処理できます。デモムービーは実際の速度なので、その速さを体感していただけると思います。写真.appから選択中の写真を取得して反転するまで一瞬です。

反転した画像をMacのOCRアプリケーション「FineReader OCR Pro」でOCR処理し、YouTubeリプレイ再生用のコードを取得します。

あとは、再生用コードをリプレイムービー検索ページのフォームに入れて、実際のYouTube上のリプレイムービーのURLにアクセス。そのまま再生するなり、ダウンロードして保存しておくことになります。


■©創通・サンライズ

本サンプルでは、AppleScriptからコントロール可能なOCRアプリケーション「FineReader OCR Pro」を用いましたが、日本語の文字列を認識しないのであれば、Web APIのOCRサービス(MicrosoftのCognitive Serviceとか)を用いてみてもよいでしょう。

あとは、全国の「戦場の絆」が導入されているゲームセンターの住所情報および緯度経度情報がストックしてあるので、それらのGPSデータと写真撮影地点とのマッチングを行なってみてもよいかもしれません(700箇所程度なので、たいした演算ではありません)。

AppleScript名:Photosで選択中の写真が指定場所から50メートル以内の場合には書き出してFineReader OCR Proで処理 v2.1
— Created 2015-12-04 by Takaaki Naganoya –v2.1
— getDistanceBetweenTwoPlaces : Created 2015-03-03 by Shane Stanley
— convAsFilteredJPEG : Created 2013-12-29 by badcharan@Twitter
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "CoreLocation"
use framework "QuartzCore"

property CIFilter : a reference to current application’s CIFilter
property NSUUID : a reference to current application’s NSUUID
property CIImage : a reference to current application’s CIImage
property NSString : a reference to current application’s NSString
property NSScanner : a reference to current application’s NSScanner
property CLLocation : a reference to current application’s CLLocation
property NSFileManager : a reference to current application’s NSFileManager
property NSCharacterSet : a reference to current application’s NSCharacterSet
property NSJPEGFileType : a reference to current application’s NSJPEGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSMutableCharacterSet : a reference to current application’s NSMutableCharacterSet
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch

set targPlace to {35.745769, 139.675565} –Game City Itabashi
set bLoc to getSelectionOnPhotos() of me –Get Location From Photo
set aDist to getDistanceBetweenTwoPlaces(targPlace, bLoc) of me

–指定地点から50メートル以内の距離で撮影された写真であれば、Exportして後続の処理を行う
if aDist is equal to false or aDist > 50 then return false

–選択中の写真のうち最初のものだけExport
set targPhotoAlias to exportSelectedPhotoOnPhotos() of me

–実験に用いた写真はそのままではOCR処理できなかったので、手っ取り早く階調反転を行う
set invertRes to convAsFilteredJPEG(targPhotoAlias, "CIColorInvert") of me
if invertRes = false then
  display dialog "Error in CIImage" with title "Error" buttons {"OK"} default button 1 with icon 2
  
return
end if
set invImage to (POSIX file invertRes) as alias

set outFileName to (NSUUID’s UUID()’s UUIDString() as text) & ".txt"
set outPath to ((path to desktop) as text) & outFileName –sandbox環境ではパスは無視される

tell application id "com.abbyy.FineReaderPro"
  activate
  
  
–Check Ready
  
set getReady to (is finereader controller active)
  
if getReady = false then return
  
  
–set idList to {English} –英語だとスペルチェックされて、"1"と"t"を誤認識するため英語の指定をやめた
  
–Caution: this command is executed asynchronously
  
–Caution: export command was changed in v12.1.4
  
  
set idList to {Basic, Java, Fortran, Cobol, Pascal} –認識ターゲット言語(C++の予約語はあるようだが、指定できないよ!)
  
open invImage — In this version ,we have to open image, at first.
  
export to txt outPath ocr languages enum idList retain layout (as plain text) encoding (utf8)
  
  
–Wait for finish
  
repeat 30 times
    set curStat to (is busy)
    
if curStat = false then exit repeat
    
delay 1
  end repeat
  
  
–sandbox環境(Mac App Store版)の場合にはファイル出力先を別途取得
  
set sandRes to (is sandboxed)
  
if sandRes = true then
    set outDir to (get output dir) as text
    
set outPath to (outDir & outFileName) as text
  end if
  
end tell

–OCR処理した結果のテキストを読み込む
tell current application
  set textRes to read file outPath
end tell

–数字ではじまる行のみを抽出して、リプレイIDを取得
set textList to paragraphs of textRes
set outList to {}
repeat with i in textList
  set j to contents of i
  
  
–1行あたりのテキストが8文字以上か?
  
if length of j > 8 then
    
    
–行頭の文字が数字か?
    
set firstChar to first character of j
    
set nRes to chkNumeric(firstChar) of me
    
if nRes = true then
      set tmp1 to text 2 thru -1 of j –最初の数字を除去
      
      
–数字とアルファベット以外の文字を削除(タブ、スペースなど)
      
set tmp2 to returnNumberAndAlphabetCharsOnly(tmp1) of me
      
if length of tmp2 ≥ 8 then
        set tmp3 to text 1 thru 8 of tmp2
        
–数字とアルファベットの混在の文字列であれば出力する
        
set tmp3Res to chkMixtureOfNumericAndAlphabet(tmp3) of me
        
if tmp3Res = true then
          set the end of outList to tmp3
        end if
      end if
    end if
  end if
end repeat

outList
–> {"4f73vg1v", "v3v32zt3", "yk1z371x", "52yzvn11", "k1ftfvvg"}–Version 1.x (3rd ID is wrong)
–> {"4f73vg1v", "v3v32zt3", "yk1z37tx", "52yzvn11", "k1ftfvvg"}– Version 2.0(Perfect!!!!)
–> {"4f73vg1v", "v3v32zt3", "yk1z37tx", "52yzvn11", "k1ftfvvg"}– Version 2.1(Perfect!!!!)
–> {"51n4gg1f", "2zxt41gg", "57k2txk9", "yy43f3gt", "4f73vg1v"} –Version 2.1(Perfect!!!!)

–Photosで選択中の写真の1枚目(複数時には無視)から緯度、経度情報を取得する
on getSelectionOnPhotos()
  tell application "Photos"
    set aa to selection
    
if aa = {} or aa = missing value then return false
    
set a to first item of aa
    
set aProp to properties of a
    
    
set aLoc to location of aProp
    
return aLoc
  end tell
end getSelectionOnPhotos

–2点間の距離を計算する
on getDistanceBetweenTwoPlaces(aPlaceLoc, bPlaceLoc)
  try
    set {aLat, aLong} to aPlaceLoc
    
set {bLat, bLong} to bPlaceLoc
  on error
    return false
  end try
  
  
set aPlace to CLLocation’s alloc()’s initWithLatitude:aLat longitude:aLong
  
set bPlace to CLLocation’s alloc()’s initWithLatitude:bLat longitude:bLong
  
set distanceInMetres to aPlace’s distanceFromLocation:bPlace
  
return (distanceInMetres as real)
end getDistanceBetweenTwoPlaces

–Photos上で選択中の写真をTemporary Folderに掘ったフォルダに書き出して、そのalias情報を返す
on exportSelectedPhotoOnPhotos()
  set dtPath to (path to temporary items) as text
  
set aUUID to NSUUID’s UUID()’s UUIDString() as text
  
  
set dirPath to ((POSIX path of dtPath) & aUUID)
  
set fileManager to NSFileManager’s defaultManager()
  
set aRes to (fileManager’s createDirectoryAtPath:dirPath withIntermediateDirectories:true attributes:(missing value) |error|:(reference))
  
set dtPath to dtPath & aUUID
  
  
tell application "Photos"
    set a to selection
    
if a = {} then return
    
set aRes to (export a to file dtPath)
  end tell
  
  
tell application "Finder"
    tell folder dtPath
      set fList to (every file) as alias list
    end tell
  end tell
  
  
if fList = {} then return false
  
return first item of fList
end exportSelectedPhotoOnPhotos

–CIFilterをかけたJPEG画像を生成
–参照:http://ashplanning.blogspot.jp/ のうちのどこか
on convAsFilteredJPEG(aPath, aFilterName)
  
  
–aliasをURL(input)とPOSIX path(output) に変換
  
set aURL to (current application’s |NSURL|’s fileURLWithPath:(POSIX path of aPath)) –Input
  
set aPOSIX to (POSIX path of aPath) & "_" & aFilterName & ".jpg" –Output
  
  
–CIImageを生成
  
set aCIImage to CIImage’s alloc()’s initWithContentsOfURL:aURL
  
  
— CIFilter をフィルタの名前で生成
  
set aFilter to CIFilter’s filterWithName:aFilterName
  
aFilter’s setDefaults() –各フィルタのパラメータはデフォルト
  
  
–Filterを実行
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
  
— NSBitmapImageRep を CIImage から生成
  
set aRep to NSBitmapImageRep’s alloc()’s initWithCIImage:aOutImage
  
  
— NSBitmapImageRep から JPEG データを取得
  
set jpegData to aRep’s representationUsingType:(NSJPEGFileType) |properties|:(missing value)
  
  
— ファイルに保存
  
set fsRes to jpegData’s writeToFile:aPOSIX atomically:true
  
if (fsRes as boolean) = false then return false –失敗した場合
  
return aPOSIX –成功した場合
  
end convAsFilteredJPEG

–数字とアルファベットの混在状態の時にtrueを返す
on chkMixtureOfNumericAndAlphabet(checkString)
  set a0Res to chkAlphabetAndNumeric(checkString) of me
  
set a1Res to chkNumeric(checkString) of me
  
set a2Res to chkAlphabet(checkString) of me
  
if {a0Res, a1Res, a2Res} = {true, false, false} then
    return true
  else
    return false
  end if
end chkMixtureOfNumericAndAlphabet

–数字のみかを調べて返す
on chkNumeric(checkString)
  set digitCharSet to NSCharacterSet’s characterSetWithCharactersInString:"0123456789"
  
set ret to my chkCompareString:checkString baseString:digitCharSet
  
return ret as boolean
end chkNumeric

— アルファベットのみか調べて返す
on chkAlphabet(checkString)
  set aStr to NSString’s stringWithString:checkString
  
set allCharSet to NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "a", 26))
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "A", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabet

— アルファベットと数字のみか調べて返す
on chkAlphabetAndNumeric(checkString)
  set aStr to NSString’s stringWithString:checkString
  
set allCharSet to NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "0", 10))
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "a", 26))
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "A", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabetAndNumeric

on chkCompareString:checkString baseString:baseString
  set aScanner to NSScanner’s localizedScannerWithString:checkString
  
aScanner’s setCharactersToBeSkipped:(missing value)
  
aScanner’s scanCharactersFromSet:baseString intoString:(missing value)
  
return (aScanner’s isAtEnd()) as boolean
end chkCompareString:baseString:

–文字置換
on repChar(aStr, targStr, repStr)
  set aString to NSString’s stringWithString:aStr
  
set bString to aString’s stringByReplacingOccurrencesOfString:targStr withString:repStr
  
return bString as text
end repChar

–アルファベットと数字以外を削除して返す
on returnNumberAndAlphabetCharsOnly(aStr)
  set anNSString to NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9A-Za-z]" withString:"" options:(NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end returnNumberAndAlphabetCharsOnly

★Click Here to Open This Script 

(Visited 39 times, 1 visits today)
Posted in file filter geolocation Image list OCR Sandbox | Tagged 10.11savvy 10.12savvy FineReader OCR Pro | Leave a comment

現在地点の緯度経度情報を取得する v2

Posted on 10月 29, 2018 by Takaaki Naganoya

WiFiの情報を元に現在地点の緯度経度情報を取得するAppleScriptです。

実行前にWiFiがオンになっている必要があるので、WiFiの状態を確認して、WiFiがオフだったらオンにする処理が必要になります。

AppleScript名:現在地点の緯度経度情報を取得する v2
— Created 2015-03-04 by Takaaki Naganoya, Shane Stanley
— Modified 2015-12-06 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "CoreLocation"

property locationManager : missing value
property curLatitude : 0
property curLongitude : 0

–Get Current Geo Location
set {aLat, aLong} to getCurrentGeoLocation() of me

on getCurrentGeoLocation()
  set locationManager to current application’s CLLocationManager’s alloc()’s init()
  
  
set locE to locationManager’s locationServicesEnabled()
  
if (locE as boolean) = true then
    locationManager’s setDelegate:me
    
locationManager’s setDesiredAccuracy:(current application’s kCLLocationAccuracyNearestTenMeters)
    
locationManager’s setDistanceFilter:500
    
locationManager’s startUpdatingLocation()
  else
    return false –error in init
  end if
  
  
set hitF to false
  
repeat 3000 times
    if {curLatitude, curLongitude} is not equal to {0, 0} then
      set hitF to true
      
exit repeat
    end if
    
delay ("0.0001" as real)
  end repeat
  
  
if hitF = false then return {false, false}
  
return {curLatitude, curLongitude}
end getCurrentGeoLocation

on locationManager:manager didUpdateLocations:locations
  set location to (locations’s lastObject())
  
set eventDate to (location’s timestamp())
  
set howRecent to (eventDate’s timeIntervalSinceNow())
  
set howRecent to howRecent as real
  
set howRecent to absNum(howRecent)
  
  
if howRecent < 15.0 then
    set alt to location’s altitude –>(NSNumber) 46.356517791748
    
set aSpeed to location’s speed –>(NSNumber) -1.0
    
set aCourse to location’s course –North:0, East:90, South:180, West:270
    
–>  (NSNumber) -1.0
    
set theDescription to location’s |description|()
    
–> (NSString) "<+35.xxxxx,+139.xxxxxx> +/- 65.00m (speed -1.00 mps / course -1.00) @ 2015/03/04 8時56分41秒 日本標準時"
    
set anNSScanner to current application’s NSScanner’s scannerWithString:theDescription
    
anNSScanner’s setCharactersToBeSkipped:(current application’s NSCharacterSet’s characterSetWithCharactersInString:"<,")
    
set {theResult, aLat} to anNSScanner’s scanDouble:(reference)
    
set {theResult, aLng} to anNSScanner’s scanDouble:(reference)
    
copy {aLat, aLng} to {my curLatitude, my curLongitude}
  else
    locationManager’s stopUpdatingLocation()
  end if
  
end locationManager:didUpdateLocations:

on locationManager:anCLLocationManager didFailWithError:anNSError
  display dialog (anNSError’s localizedDescription() as text)
end locationManager:didFailWithError:

on absNum(aNum)
  if aNum > 0 then
    return aNum
  else
    return (aNum * -1)
  end if
end absNum

★Click Here to Open This Script 

(Visited 36 times, 1 visits today)
Posted in geolocation System WiFi | Tagged 10.11savvy 10.12savvy 10.13savvy CLLocationManager NSCharacterSet NSScanner | Leave a comment

日本測地系から世界測地系への座標変換

Posted on 7月 14, 2018 by Takaaki Naganoya

日本測地系の緯度・経度情報から世界測地系の緯度・経度情報に変換するAppleScriptです。

AppleScriptに35種類の関数計算機能を付加する「calcLibAS」の計算精度を確認するための実例でもあります。だいたい期待の精度は出せている感じです。

より精度を求められるような用途には、AppleScriptの数値変数自体が浮動小数点演算で10桁の計算精度しかないので、数値計算自体を外部にすべて出してしまうか、より精度の高い変数型を作ってしまうか(文字列で扱うようにすれば問題なさそう)というところでしょうか。

「日本測地系から世界測地系への座標変換(近似式)」のほうはObjective-Cから、「日本測地系から世界測地系への直行座標変換」のほうはRubyからAppleScriptに書き換えてみたものです。

Rubyのプログラムが割と単調だったので、読んでいて疲れてしまいました。変数名の付け方が途中で変わっているのは、「とりあえず動けばいい」ぐらいで組んでいたのと、変数名にいちいち「Local」とか付けるのに疲れたからです。

Piyomaru Script Assistantで変数名のみ一括置換してもいいわけですが、それはそれ、、、

AppleScript名:日本測地系から世界測地系への座標変換(近似式)
— Created 2018-07-13 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set jpLat to 42.16593046887
set jpLng to 142.771877437246
set {wdLat, wdLng, wdH} to tky2wgsLinea(jpLat, jpLng, 0) of me –日本測地系から世界測地系に換算
–>  {​​​​​42.168515890674, ​​​​​142.768119997121, ​​​​​0​​​}

set {latJ, lonJ, heightJ} to wgs2tkyLinea(wdLat, wdLng, wdH) of me –世界測地系から日本測地系に換算
–>  {​​​​​42.16593052955, ​​​​​142.77187743437, ​​​​​0​​​}

–日本測地系から世界測地系に換算
–http://d.hatena.ne.jp/iRSS/20111112/1321113232
on tky2wgsLinea(latJ, lonJ, heightJ)
  set heightW to heightJ
  
set lonW to lonJ – latJ * 4.6038E-5 – lonJ * 8.3043E-5 + 0.01004
  
set latW to latJ – latJ * 1.0695E-4 + lonJ * 1.7464E-5 + 0.0046017
  
return {latW, lonW, heightW}
end tky2wgsLinea

–世界測地系から日本測地系に換算
–https://altarf.net/computer/技術的なポエム/3332
on wgs2tkyLinea(latW, lonW, heightW)
  set heightJ to heightW
  
set latJ to (latW * 1.000106961) – (lonW * 1.7467E-5) – 0.004602017
  
set lonJ to (lonW * 1.000083049) + (latW * 4.6047E-5) – 0.010041046
  
return {latJ, lonJ, heightJ}
end wgs2tkyLinea

★Click Here to Open This Script 

AppleScript名:日本測地系から世界測地系への直行座標変換
— Created 2018-07-13 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use math : script "calcLibAS" –http://piyocast.com/as/archives/3523

set jpLat to 42.16593046887
set jpLng to 142.771877437246

set {wdLat, wdLng, wdH} to JapanGeodeticSystem’s convertIntoWgs(jpLat, jpLng)
–>  {​​​​​42.168504277889, ​​​​​142.768075650137, ​​​​​61.914452206343​​​}

–https://altarf.net/computer/ruby/3347
–日本測地系から世界測地系に換算
script JapanGeodeticSystem
  –ラジアン(度)
  
property rdNum : pi / 180
  
  
–日本測地系の定数(ベッセル楕円体)
  
property rJP : 6.377397155E+6 –赤道半径
  
property fJP : 1 / 299.1528128 –扁平率
  
property e2JP : (2 * fJP) – (fJP * fJP) –第一離心率
  
  
–世界測地系の定数(WGS84)
  
property rWS : 6.378137E+6 –赤道半径
  
property fWS : 1 / 298.257223563 –扁平率
  
property e2WS : (2 * fWS) – (fWS * fWS) –第一離心率
  
  
–並行移動量(m)
  
property dxNum : -148
  
property dyNum : 507.0
  
property dzNum : 681.0
  
  
–楕円体高
  
property heightNum : 0
  
  
  
–日本測地系から世界測地系に変換する
  
on convertIntoWgs(aLat, aLong)
    set {x, y, z} to llh2xyz(aLat, aLong, heightNum, rJP, e2JP, rdNum) of me
    
    
set x to x + dxNum
    
set y to y + dyNum
    
set z to z + dzNum
    
    
set {lat1, lng1, h1} to xyz2llh(x, y, z, rWS, e2WS, rdNum) of me
    
return {lat1, lng1, h1}
  end convertIntoWgs
  
  
  
–座標系の変換(緯度経度 -> xyz)
  
on llh2xyz(latLocal, lngLocal, hLocal, aLocal, e2Local, rdLocal)
    set latLocal to latLocal * rdLocal
    
set lngLocal to lngLocal * rdLocal
    
    
set sbNum to calcSin(latLocal) of math
    
set cbNum to calcCos(latLocal) of math
    
    
set rnLocal to aLocal / (calcSqrt(1 – e2Local * sbNum * sbNum) of math)
    
    
set xLocal to (rnLocal + hLocal) * cbNum * (calcCos(lngLocal) of math)
    
set yLocal to (rnLocal + hLocal) * cbNum * (calcSin(lngLocal) of math)
    
set zLocal to (rnLocal * (1 – e2Local) + hLocal) * sbNum
    
    
return {xLocal, yLocal, zLocal}
  end llh2xyz
  
  
  
–座標系の変換(xyz -> 緯度経度)
  
on xyz2llh(x, y, z, a, e2, rdLocal)
    set bda to calcSqrt(1 – e2) of math
    
set p to calcSqrt(x * x + y * y) of math
    
set t to calcAtan2(z, p * bda) of math
    
set stNum to calcSin(t) of math
    
set ctNum to calcCos(t) of math
    
set b to calcAtan2(z + e2 * a / bda * stNum * stNum * stNum, p – e2 * a * ctNum * ctNum * ctNum) of math
    
    
set l to calcAtan2(y, x) of math
    
set sb to calcSin(b) of math
    
set rn to a / (calcSqrt(1 – e2 * sb * sb) of math)
    
set h to p / (calcCos(b) of math) – rn
    
set l1 to b / rdLocal
    
set l2 to l / rdLocal
    
return {l1, l2, h}
  end xyz2llh
  
end script

★Click Here to Open This Script 

(Visited 769 times, 1 visits today)
Posted in geolocation | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

1箇所から別の箇所の方位を求める v2

Posted on 5月 12, 2018 by Takaaki Naganoya

任意の緯度・経度情報から、別の箇所の緯度・経度情報の「方位」を計算するAppleScriptです。

v1では、Satimage OSAXのインストールが必要でしたが、自前でObjective-Cで書いた「atan2だけを計算するフレームワーク」に置き換えたものです。

–> trigonometry.framework (To ~/Library/Frameworks/)

北を0として、西に向かうとマイナス、東に向かうとプラスの値で角度(方位)を返します。この手の計算に必須のatan2関数がAppleScriptに標準装備されていないため、atan2を呼び出すだけの簡単なCocoa FrameworkをObjective-Cで記述して、呼び出してみました。

→ のちにこれを、FrameworkもBdridgePlusも使わない、自前の関数計算ライブラリ「calcLibAS」を使って計算するように書き換えたサンプル「Calc direction from place A to B」を掲載しています

AppleScript名:1箇所から別の箇所の方位を求める v2
— Created 2018-05-10 by Takaaki Naganoya
— 2017-2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "trigonometry" –(for atan2 calculation)
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

set coord1 to {latitude:35.73677496, longitude:139.63754457} –Nakamurabashi Sta.
set coord2 to {latitude:35.78839012, longitude:139.61241447} –Wakoshi Sta.
set dirRes1 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  -25.925429877542

set coord2 to {latitude:35.7227821, longitude:139.63860897} –Saginomiya Sta.
set dirRes2 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  175.649833487804

set coord2 to {latitude:35.73590542, longitude:139.62986745} –Fujimidai Sta.
set dirRes3 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  -96.385293928667

set coord2 to {latitude:35.73785024, longitude:139.65339321} –Nerima Sta.
set dirRes4 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  85.959474671834

set coord2 to {latitude:35.71026838, longitude:139.81215754} –Tokyo Sky Tree
set dirRes5 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  96.826542737106

–位置情報1から位置情報2の方角を計算。北が0度
on calcDirectionBetweenTwoPlaces(coord1, coord2)
  load framework –BridgePlus
  
set deltaLong to (longitude of coord2) – (longitude of coord1)
  
set yComponent to bPlus’s sinValueOf:deltaLong
  
set xComponent to (bPlus’s cosValueOf:(latitude of coord1)) * (bPlus’s sinValueOf:(latitude of coord2)) – (bPlus’s sinValueOf:(latitude of coord1)) * (bPlus’s cosValueOf:(latitude of coord2)) * (bPlus’s cosValueOf:deltaLong)
  
  
set radians to (current application’s calcAtan2’s atan2Num:yComponent withNum:xComponent) as real
  
set degreeRes to (radToDeg(radians) of me)
  
  
return degreeRes
end calcDirectionBetweenTwoPlaces

on radToDeg(aRadian)
  return aRadian * (180 / pi)
end radToDeg

★Click Here to Open This Script 

(Visited 49 times, 2 visits today)
Posted in geolocation | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Geofenceを付けつつReminder項目を追加

Posted on 5月 5, 2018 by Takaaki Naganoya

Reminders.app(リマインダー)に新規リマインド項目を作成し、Geofenceを設定するAppleScriptです。

Reminders.appのAppleScript用語辞書にはGeofence作成機能は用意されていないため、Cocoaの機能を利用して追加しました。

Geofenceは、指定の緯度・経度のポイントから半径xxxメートルの円の中に入る場合に発生するアラーム(Enter Alarm)、脱出する場合に発生するアラーム(Leave Alarm)の2種類を設定できます。

Mac上のReminders.app上で登録したこのリマインド項目がiCloud経由でiPhoneにシンクロされ、iPhoneを持って当該期間中に指定場所に行って半径200メートルの円の中から出るとアラームが表示されることになります。

AppleScript名:Geofenceを付けつつReminder項目を追加
— Created 2014-12-08 by Shane Stanley
— Modified 2015-09-24 by Takaaki Naganoya –Geofence Alarm
— Modified 2015-09-24 by Shane Stanley –Fix the way to Create the geofence alarm
— Modified 2015-09-24 by Takaaki Naganoya –change and test for El Capitan’s Enum bridging
–Reference:
–http://stackoverflow.com/questions/26903847/add-location-to-ekevent-ios-calendar
–http://timhibbard.com/blog/2013/01/03/how-to-create-remove-and-manage-geofence-reminders-in-ios-programmatically-with-xcode/
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "EventKit"

property EKAlarm : a reference to current application’s EKAlarm
property CLLocation : a reference to current application’s CLLocation
property EKEventStore : a reference to current application’s EKEventStore
property EKStructuredLocation : a reference to current application’s EKStructuredLocation
property EKEntityMaskReminder : a reference to current application’s EKEntityMaskReminder
property EKAlarmProximityEnter : a reference to current application’s EKAlarmProximityEnter
property EKAlarmProximityLeave : a reference to current application’s EKAlarmProximityLeave

–Start Date
set dSt to "2018/06/01 00:00:00"
set dateO1 to date dSt

–End Date
set dSt2 to "2018/08/01 00:00:00"
set dateO2 to date dSt2

tell application "Reminders"
  if not (exists list "test") then
    make new list with properties {name:"test"}
  end if
  
  
tell list "test"
    set aReminder to (make new reminder with properties {name:"Test1", body:"New Reminder", due date:dateO2, remind me date:dateO1, priority:9}) –priority 1:高、5:中、9:低、0:なし
    
set anID to id of aReminder
    
–> "x-apple-reminder://XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  end tell
end tell

set theID to text 20 thru -1 of anID
my setLocationToLeaveForReminderID(35.745769, 139.675565, "Target Place", theID, 200)

–指定場所に到着した時に発動するGeofence Alarmを指定のリマインダーに登録する。Geofence半径指定つき(単位:メートル)
on setLocationToEnterForReminderID(aLatitude, aLongitude, aTitle, theID, aRangeByMeter)
  — Get event store
  
set eventStore to EKEventStore’s alloc()’s initWithAccessToEntityTypes:(EKEntityMaskReminder)
  
  
— Get the reminder
  
set theReminder to eventStore’s calendarItemWithIdentifier:theID
  
  
–Create the geofence alarm
  
set enterAlarm to EKAlarm’s alarmWithRelativeOffset:0
  
enterAlarm’s setProximity:(EKAlarmProximityEnter)
  
set structLoc to EKStructuredLocation’s locationWithTitle:aTitle
  
set aLoc to CLLocation’s alloc()’s initWithLatitude:aLatitude longitude:aLongitude
  
structLoc’s setGeoLocation:aLoc
  
  
— Set radius by meters
  
structLoc’s setRadius:aRangeByMeter
  
enterAlarm’s setStructuredLocation:structLoc
  
  
theReminder’s addAlarm:enterAlarm
  
set aRes to eventStore’s saveReminder:theReminder commit:true |error|:(missing value)
  
  
return aRes as boolean
end setLocationToEnterForReminderID

–指定場所を出発した時に発動するGeofence Alarmを指定のリマインダーに登録する。Geofence半径指定つき(単位:メートル)
on setLocationToLeaveForReminderID(aLatitude, aLongitude, aTitle, theID, aRangeByMeter)
  — Get event store; 1 means reminders
  
set eventStore to EKEventStore’s alloc()’s initWithAccessToEntityTypes:(EKEntityMaskReminder)
  
  
— Get the reminder
  
set theReminder to eventStore’s calendarItemWithIdentifier:theID
  
  
–Create the geofence alarm
  
set leaveAlarm to EKAlarm’s alarmWithRelativeOffset:0
  
leaveAlarm’s setProximity:(EKAlarmProximityLeave)
  
set structLoc to EKStructuredLocation’s locationWithTitle:aTitle
  
set aLoc to CLLocation’s alloc()’s initWithLatitude:aLatitude longitude:aLongitude
  
structLoc’s setGeoLocation:aLoc
  
  
— Set radius by meters
  
structLoc’s setRadius:aRangeByMeter
  
leaveAlarm’s setStructuredLocation:structLoc
  
  
theReminder’s addAlarm:leaveAlarm
  
set aRes to eventStore’s saveReminder:theReminder commit:true |error|:(missing value)
  
  
return aRes as boolean
end setLocationToLeaveForReminderID

★Click Here to Open This Script 

(Visited 41 times, 1 visits today)
Posted in Calendar geolocation | Tagged 10.11savvy 10.12savvy 10.13savvy Reminders | Leave a comment

(GET)国土地理院APIで現在位置の標高を取得する

Posted on 3月 2, 2018 by Takaaki Naganoya

国土地理院のREST API「標高API」を呼んで、現在位置の標高を取得するAppleScriptです。

現在位置の取得のためにMac本体のWiFiがオンになっている必要があります。

AppleScript名:(GET)国土地理院APIで現在位置の標高を取得する
— Created 2016-10-29 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "CoreLocation"
use framework "CoreWLAN"
–http://maps.gsi.go.jp/development/api.html

property locationManager : missing value
property curLatitude : 0
property curLongitude : 0

set reqURLStr to "http://cyberjapandata2.gsi.go.jp/general/dem/scripts/getelevation.php"

–現在地の緯度、経度情報を取得する
set {aLat, aLong} to getCurrentLocation() of me

set aRec to {lon:aLong as string, lat:aLat as string, outtype:"JSON"}
set aURL to retURLwithParams(reqURLStr, aRec) of me
set aRes to callRestGETAPIAndParseResults(aURL) of me

set aRESTres to (json of aRes) as record
return aRESTres
–>  {​​​​​hsrc:"5m(レーザ)", ​​​​​elevation:40.4​​​}

–set aRESCode to responseCode of aRes
–>  200

–set aRESHeader to responseHeader of aRes
–>  {​​​​​Server:"Apache/2.4.10 (Debian) PHP/5.6.19", ​​​​​Content-Type:"application/json; charset=utf-8", ​​​​​X-Powered-By:"PHP/5.6.19", ​​​​​Connection:"Keep-Alive", ​​​​​Access-Control-Allow-Origin:"*", ​​​​​Date:"Sat, 29 Oct 2016 10:53:14 GMT", ​​​​​Content-Encoding:"gzip", ​​​​​Content-Length:"71", ​​​​​Keep-Alive:"timeout=5, max=100", ​​​​​Vary:"Accept-Encoding"​​​}

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on urlencodeStr(aStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set aString to (aString’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s URLQueryAllowedCharacterSet())) as text
  
return aString
end urlencodeStr

on getCurrentLocation()
  activeWiFiPower() of me
  
  
set locationManager to current application’s CLLocationManager’s alloc()’s init()
  
  
set locE to locationManager’s locationServicesEnabled()
  
if (locE as boolean) = true then
    locationManager’s setDelegate:me
    
locationManager’s setDesiredAccuracy:(current application’s kCLLocationAccuracyNearestTenMeters)
    
locationManager’s setDistanceFilter:500
    
locationManager’s startUpdatingLocation()
  else
    return false –error in init
  end if
  
  
set hitF to false
  
repeat 3000 times
    if {curLatitude, curLongitude} is not equal to {0, 0} then
      set hitF to true
      
exit repeat
    end if
    
delay 0.01
  end repeat
  
  
if hitF = false then return false
  
return {curLatitude, curLongitude}
  
end getCurrentLocation

—-以下、curLocationLibの内容

on locationManager:manager didUpdateLocations:locations
  
  
–Listing 1-3 Processing an incoming location event
  
set location to (locations’s lastObject())
  
set eventDate to (location’s timestamp())
  
set howRecent to (eventDate’s timeIntervalSinceNow())
  
  
–Calc ABS
  
set howRecent to howRecent as real
  
set howRecent to absNum(howRecent)
  
log howRecent
  
  
if howRecent < 15.0 then
    
    
set alt to location’s altitude
    
–>  (NSNumber) 46.356517791748
    
    
set aSpeed to location’s speed
    
–>  (NSNumber) -1.0
    
    
set aCourse to location’s course –North:0, East:90, South:180, West:270
    
–>  (NSNumber) -1.0
    
    
–By Shane Stanley
    
set theDescription to location’s |description|()
    
–> (NSString) "<+35.xxxxx,+139.xxxxxx> +/- 65.00m (speed -1.00 mps / course -1.00) @ 2015/03/04 8時56分41秒 日本標準時"
    
    
set anNSScanner to current application’s NSScanner’s scannerWithString:theDescription
    
anNSScanner’s setCharactersToBeSkipped:(current application’s NSCharacterSet’s characterSetWithCharactersInString:"<,")
    
set {theResult, aLat} to anNSScanner’s scanDouble:(reference)
    
set {theResult, aLng} to anNSScanner’s scanDouble:(reference)
    
    
copy {aLat, aLng} to {my curLatitude, my curLongitude}
    
  else
    log {"stopUpdatingLocation"}
    
locationManager’s stopUpdatingLocation()
  end if
  
end locationManager:didUpdateLocations:

on locationManager:anCLLocationManager didFailWithError:anNSError
  display dialog (anNSError’s localizedDescription() as text)
end locationManager:didFailWithError:

on absNum(aNum)
  if aNum > 0 then
    return aNum
  else
    return (aNum * -1)
  end if
end absNum

—Activate WiFi Power

on activeWiFiPower()
  set dName to getWiFiDeviceName() of me
  
set aInterface to current application’s CWInterface’s alloc()’s initWithInterfaceName:dName
  
set aPowerStat to (aInterface’s powerOn()) as boolean
  
if aPowerStat = false then
    set wRes to aInterface’s setPower:true |error|:(missing value)
    
if wRes = missing value then
      error "Can’t power on WiFi Interface."
    end if
  end if
end activeWiFiPower

–指定ハードウェアポートのデバイス名を取得する
on getWiFiDeviceName()
  set v2 to system attribute "sys2" –> 4
  
if v2 ≤ 6 then
    set hardWareName to "AirPort" –Under Mac OS X 10.6.8
    
set aMesStr to "Current AirPort Network: "
  else if v2 ≥ 7 then
    set hardWareName to "Wi-Fi" –Mac OS X 10.7 or later
    
set aMesStr to "Current Wi-Fi Network: "
  else
    display dialog "error"
  end if
  
  
set dName to getHardwareDeviceName(hardWareName) of me
  
return dName
end getWiFiDeviceName

–指定ハードウェアポートのデバイス名を取得する
on getHardwareDeviceName(targName)
  set sRes to do shell script "/usr/sbin/networksetup -listallhardwareports"
  
log sRes
  
set sList to paragraphs of sRes
  
set s1List to items 2 thru -1 of sList
  
  
set s2List to {}
  
repeat with i in s1List
    set j to contents of i
    
if j is equal to "VLAN Configurations" then
      exit repeat
    end if
    
set the end of s2List to j
  end repeat
  
  
–ネットワークポート関連のレコードを作成
  
set s3List to {}
  
set aLen to length of s2List
  
repeat with i from 1 to aLen by 4
    set a1Item to contents of item i of s2List
    
set a1Item to repChar(a1Item, "Hardware Port: ", "") of me
    
    
set a2Item to contents of item (i + 1) of s2List
    
set a2Item to repChar(a2Item, "Device: ", "") of me
    
    
set a3Item to contents of item (i + 2) of s2List
    
set a3Item to repChar(a3Item, "Ethernet Address: ", "") of me
    
    
set the end of s3List to {hardwarePort:a1Item, device:a2Item, ethernetAddress:a3Item}
  end repeat
  
  
repeat with i in s3List
    set j1 to hardwarePort of i
    
set j2 to device of i
    
if j1 is equal to targName then
      return j2
    end if
  end repeat
  
  
return ""
  
end getHardwareDeviceName

–文字置換ルーチン
on repChar(origText, targStr, repStr)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChar

★Click Here to Open This Script 

(Visited 79 times, 1 visits today)
Posted in geolocation Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

1箇所から別の箇所の方位を求める

Posted on 2月 8, 2018 by Takaaki Naganoya

任意の緯度・経度情報から、別の箇所の緯度・経度情報の「方位」を計算するAppleScriptです。

北を0として、西に向かうとマイナス、東に向かうとプラスの値で角度(方位)を返します。この手の計算に必須のatan2関数がAppleScriptに標準装備されていないため、atan2の機能を提供するSatimage OSAXを実行環境にインストールしておく必要があります。

各種三角関数に関しては、直接計算する関数がなくても、あらかじめ計算しておいてテーブルから取得する程度でも精度的には問題のないケースが多いので、テーブルでデータを持っておくことも多々あります。

最近、Numbersで内蔵関数を増やすために利用している「cephes math library」あたりがCレベルではなくObjective-Cレベルから直接利用できるとよさそうなのですが、、、

AppleScript名:1箇所から別の箇所の方位を求める
— Created 2017-04-27 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions –requires "Satimage osax" http://www.satimage.fr/software/en/downloads/downloads_companion_osaxen.html
use framework "Foundation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html
–http://zurb.com/forrst/posts/Direction_between_2_CLLocations-uAo

set coord1 to {latitude:35.73677496, longitude:139.63754457} –中村橋駅
set coord2 to {latitude:35.78839012, longitude:139.61241447} –和光市駅
set dirRes to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  -25.925429877542

(*)
set coord2 to {latitude:35.78839012, longitude:139.61241447} –和光市駅
set dirRes to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  -25.925429877542

set coord2 to {latitude:35.7227821, longitude:139.63860897} –鷺宮駅
set dirRes to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  175.649833487804

set coord2 to {latitude:35.73590542, longitude:139.62986745} –富士見台駅
set dirRes to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  -96.385293928667

set coord2 to {latitude:35.73785024, longitude:139.65339321} –練馬駅
set dirRes to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  85.959474671834

set coord2 to {latitude:35.71026838, longitude:139.81215754} –東京スカイツリー
set dirRes to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  96.826542737106
*)

–位置情報1から位置情報2の方角を計算。北が0度
on calcDirectionBetweenTwoPlaces(coord1, coord2)
  load framework
  
set deltaLong to (longitude of coord2) – (longitude of coord1)
  
set yComponent to bPlus’s sinValueOf:deltaLong
  
set xComponent to (bPlus’s cosValueOf:(latitude of coord1)) * (bPlus’s sinValueOf:(latitude of coord2)) – (bPlus’s sinValueOf:(latitude of coord1)) * (bPlus’s cosValueOf:(latitude of coord2)) * (bPlus’s cosValueOf:deltaLong)
  
  
set vList to {yComponent, xComponent}
  
set radians to atan2 vList —Requires SatImage OSAX
  
set degreeRes to (radToDeg(radians) of me)
  
  
return degreeRes
end calcDirectionBetweenTwoPlaces

on radToDeg(aRadian)
  return aRadian * (180 / pi)
end radToDeg

★Click Here to Open This Script 

(Visited 112 times, 1 visits today)
Posted in geolocation | Tagged 10.11savvy 10.12savvy 10.13savvy | 2 Comments

Post navigation

  • Older posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • AppleScriptによるWebブラウザ自動操縦ガイド
  • macOS 13, Ventura(継続更新)
  • ドラッグ&ドロップ機能の未来?
  • macOS 12.x上のAppleScriptのトラブルまとめ
  • PFiddlesoft UI Browserが製品終了に
  • macOS 12.3 beta 5、ASの障害が解消される(?)
  • SF Symbolsを名称で指定してPNG画像化
  • 新刊発売:AppleScriptによるWebブラウザ自動操縦ガイド
  • macOS 12.3上でFinder上で選択中のファイルをそのままオープンできない件
  • Pixelmator Pro v2.4.1で新機能追加+AppleScriptコマンド追加
  • Safariで表示中のYouTubeムービーのサムネイル画像を取得
  • macOS 12のスクリプトエディタで、Context Menu機能にバグ
  • 人類史上初、魔導書の観点から書かれたAppleScript入門書「7つの宝珠」シリーズ開始?!
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 12.5(21G72)がリリースされた!
  • Pages v12に謎のバグ。書類上に11枚しか画像を配置できない→解決
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • macOS 13 TTS Voice環境に変更
  • NSCharacterSetの使い方を間違えた

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1391) 10.14savvy (586) 10.15savvy (434) 11.0savvy (274) 12.0savvy (174) 13.0savvy (34) CotEditor (60) Finder (47) iTunes (19) Keynote (97) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (21) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (42) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (118) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSUUID (18) NSView (33) NSWorkspace (20) Numbers (55) Pages (36) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • 登録
  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • 登録
  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC