Skip to content

Instantly share code, notes, and snippets.

@atskimura
Created December 4, 2022 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atskimura/0e7f0516bc38bc84b8f8a4e2d1edef9a to your computer and use it in GitHub Desktop.
Save atskimura/0e7f0516bc38bc84b8f8a4e2d1edef9a to your computer and use it in GitHub Desktop.
ChatGPTが生成した取引先の請求先住所に緯度経度を保存するApexトリガー
// トリガーを作成する対象のオブジェクトとフィールド
trigger UpdateGeocode on Account (after update) {
// トリガーが実行される条件を指定する
for (Account a : Trigger.new) {
if (a.BillingStreet != Trigger.oldMap.get(a.Id).BillingStreet ||
a.BillingCity != Trigger.oldMap.get(a.Id).BillingCity ||
a.BillingState != Trigger.oldMap.get(a.Id).BillingState ||
a.BillingCountry != Trigger.oldMap.get(a.Id).BillingCountry ||
a.BillingPostalCode != Trigger.oldMap.get(a.Id).BillingPostalCode) {
// Google Geocoding API のエンドポイント URL
String geocodeEndpoint = 'https://maps.googleapis.com/maps/api/geocode/json';
// API リクエスト用のパラメータを設定する
String address = '';
if (!String.isBlank(a.BillingStreet)) {
address += a.BillingStreet + ',';
}
if (!String.isBlank(a.BillingCity)) {
address += a.BillingCity + ',';
}
if (!String.isBlank(a.BillingState)) {
address += a.BillingState + ',';
}
if (!String.isBlank(a.BillingCountry)) {
address += a.BillingCountry + ',';
}
if (!String.isBlank(a.BillingPostalCode)) {
address += a.BillingPostalCode;
}
String queryString = 'address=' + EncodingUtil.urlEncode(address, 'UTF-8') + '&key=YOUR_API_KEY';
// HTTP リクエストを実行する
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint(geocodeEndpoint + '?' + queryString);
request.setMethod('GET');
HttpResponse response = http.send(request);
// API のレスポンスを処理する
if (response.getStatusCode() == 200) {
// レスポンスボディを JSON として解析する
Map<String, Object> json = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
// API のレスポンスステータスが "OK" であることを確認する
if (json.get('status') == 'OK') {
// レスポンスから住所の緯度と経度を取得する
List<Object> results = (List<Object>) json.get('results');
Map<String, Object> result = (Map<String, Object>) results[0];
Map<String, Object> geometry = (Map<String, Object>) result.get('geometry');
Map<String, Object> location = (Map<String, Object>) geometry.get('location');
Double latitude = (Double) location.get('lat');
Double longitude = (Double) location.get('lng');
// 取得した緯度と経度を取引先レコードに保存する
a.BillingLatitude = latitude;
a.BillingLongitude = longitude;
}
}
}
}
// 変更した取引先レコードを保存する
update Trigger.new;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment