如何在没有Google地图的情况下计算边界中心?

时间:2015-03-28 21:02:52

标签: google-maps latitude-longitude bounds

我有以下界限:

var bounds = {
    southwest: {lat: 54.69726685890506, lng: -2.7379201682812226},
    northeast: {lat: 55.38942944437183, lng: -1.2456105979687226}
};

通过使用谷歌地图API,我可以像下面这样计算上面边界的慢跑:

// returns (55.04334815163844, -1.9917653831249726)
(new google.maps.LatLngBounds(bounds.southeast, bounds.northeast)).getCenter();

如何在不使用google.maps.LatLngBounds.getCenter但数学?

的情况下计算边界中心

我需要编写“魔术”函数,返回相同的中心纬度,像google.maps.LatLngBounds.getCenter一样:

function getBoundsCenter(bounds) {
    // need to calculate and return center of passed bounds;    
}

var center = getBoundsCenter(bounds); // center should be (55.04334815163844, -1.9917653831249726) 

1 个答案:

答案 0 :(得分:9)

var bounds = {
    southwest: {lat: 54.69726685890506, lng: -2.7379201682812226},
    northeast: {lat: 55.38942944437183, lng: -1.2456105979687226}
};

center lat = (southwest.lat + northeast.lat)/2 = 55.043348151638
center lng = (southwest.lng + northeast.lng)/2 = -1.991765383125

如果您需要跨越国际日期变更线:

如果两个经度之间的差异大于180度,则通过向模数360的每个数字加360来将范围从-180移至+180到360:

  if ((bounds.southwest.lng - bounds.northeast.lng > 180) || 
      (bounds.northeast.lng - bounds.southwest.lng > 180))
  {
    bounds.southwest.lng += 360;
    bounds.southwest.lng %= 360;
    bounds.northeast.lng += 360;
    bounds.northeast.lng %= 360;
  }

proof of concept fiddle(在Google Maps Javascript API v3地图上显示结果,但不需要API)

代码段

console.log("original bounds in question");
var bounds = {
  southwest: {
    lat: 54.69726685890506,
    lng: -2.7379201682812226
  },
  northeast: {
    lat: 55.38942944437183,
    lng: -1.2456105979687226
  }
};

if ((bounds.southwest.lng - bounds.northeast.lng > 180) || (bounds.northeast.lng - bounds.southwest.lng > 180)) {
  bounds.southwest.lng += 360;
  bounds.southwest.lng %= 360;
  bounds.northeast.lng += 360;
  bounds.northeast.lng %= 360;
}
var center_lat = (bounds.southwest.lat + bounds.northeast.lat) / 2; // = 55.043348151638
console.log("center_lat=" + center_lat);
var center_lng = (bounds.southwest.lng + bounds.northeast.lng) / 2; // = -1.991765383125
console.log("center_lng=" + center_lng);

console.log("bounds in crossing International Date Line");
var bounds = {
  southwest: {
    lat: 54.69726685890506,
    lng: -182.7379201682812226
  },
  northeast: {
    lat: 55.38942944437183,
    lng: 181.2456105979687226
  }
};

if ((bounds.southwest.lng - bounds.northeast.lng > 180) || (bounds.northeast.lng - bounds.southwest.lng > 180)) {
  bounds.southwest.lng += 360;
  bounds.southwest.lng %= 360;
  bounds.northeast.lng += 360;
  bounds.northeast.lng %= 360;
}
var center_lat = (bounds.southwest.lat + bounds.northeast.lat) / 2; // = 55.043348151638
console.log("center_lat=" + center_lat);
var center_lng = (bounds.southwest.lng + bounds.northeast.lng) / 2; // = -1.991765383125
console.log("center_lng=" + center_lng);