通过两个坐标点计算方向(dart 版本)
ON THIS PAGE
stackoverflow 看到 JS 版本的实现
https://stackoverflow.com/questions/8502795/get-direction-compass-with-two-longitude-latitude-points
//example obj data containing lat and lng points
//stop location - the radii end point
endpoint.lat = 44.9631;
endpoint.lng = -93.2492;
//bus location from the southeast - the circle center
startpoint.lat = 44.95517;
startpoint.lng = -93.2427;
function vehicleBearing(endpoint, startpoint) {
endpoint.lat = x1;
endpoint.lng = y1;
startpoint.lat = x2;
startpoint.lng = y2;
var radians = getAtan2((y1 - y2), (x1 - x2));
function getAtan2(y, x) {
return Math.atan2(y, x);
};
var compassReading = radians * (180 / Math.PI);
var coordNames = ["N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"];
var coordIndex = Math.round(compassReading / 45);
if (coordIndex < 0) {
coordIndex = coordIndex + 8
};
return coordNames[coordIndex]; // returns the coordinate value
}
翻译成 Dart
import 'dart:math';
void main() {
String direction = vehicleBearing(39,116, 40, 116);
print(direction);
}
String vehicleBearing (double start_lat, double start_lng, double end_lat, double end_lng) {
double radians = atan2((end_lng - start_lng), (end_lat - start_lat));
double compassReading = radians * (180 / pi);
List<String> coordNames = ["N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"];
int coordIndex = (compassReading / 45).round();
if (coordIndex < 0) {
coordIndex = coordIndex + 8;
};
return coordNames[coordIndex];
}
如果需要输出中文,修改方向列表即可
["北", "东北", "东", "东南","南","西南","西","西北","北"];
2021-08-26