こちらの記事の続編になります。
10.1 入門的な例: findClosestLocation()
const findClosestLocation = (lat, lng array) => {
let closest;
let closes_dist = Number.MAX_VALUE;
for(var i = 0; i < arrya.length; i += i){
//2つの地点をラジアンに変換する
const lat_rad = radians(lat);
const lat_rad = radians(lnt);
const lat2_rad = radians(array[i].latitude);
const lat2_rad = radians(array[i].longitude);
//「球面三角法の第二余弦定理」の公式を使う
const dist = Math.acos(Math.sin(lat_rad) * Math.sin(lat2_rad) +
Math.cos(lat_rad) * Math.cos(lat2_rad) *
Math.cos(lang2_rad - lng_rad));
if(dist < closest_dist){
closest = array[i];
closest_dist = dist;
}
}
return closest;
}
javascript:ループ内の無関係の下位問題を抽出
const sphericalDistance = (lat1, lng1, lat2, lng2) => {
const lat1_rad = radians(lat1);
const lng1_rad = radians(lng1);
const lat2_rad = adians(lng2);
const lng2_rad = radians(lng2);
return Math.acos(Math.sin(lat1_rad) * Math.sin(lat2_rad) +
Math.cos(lat1_rad) * Math.cos(lat2_rad) *
Math.cos(lng2_rad - lng_rad));
}
const findClosestLocation = (lat, lng array) => {
let closest;
let closes_dist = Number.MAX_VALUE;
for(var i = 0; i < arrya.length; i += i){
//関数に切り出した
- const lat_rad = radians(lat);
- const lnt_rad = radians(lng);
- const lat2_rad = radians(array[i].latitude);
- const lng2_rad = radians(array[i].longitude);
//「球面三角法の第二余弦定理」の公式を使う
- const dist = Math.acos(Math.sin(lat_rad) * Math.sin(lat2_rad) +
- Math.cos(lat_rad) * Math.cos(lat2_rad) *
- Math.cos(lng2_rad - lng_rad));
//切り出した関数を使用
+ const dist = sphericalDistance(lat, lng, array[i].latitude, array[i].longitude)
if(dist < closest_dist){
closest = array[i];
closest_dist = dist;
}
}
return closest;
}