Finding the center of a map

时间:2019-04-17 00:57:35

标签: javascript arrays json loops

Before this part, I made a master array that contain latitude, longitude and type form a public JSON API(https://data.buffalony.gov/resource/v5df-q4ru.json).

What I mean by master array is the following..

[["latitude","longitude","type"]...] // "..." represent more of 
//those single list containing latitude, longitude and type.  

To find the center point, I will need to find the largest and smallest latitude and longitude in the master array. The center point will be the average of that largest and smallest value.

I did the following but I believe that there's a better way of doing it.

function findMapCenter(master){
  for (var key in Object.keys(master)){
    var lat = master([key]["latitude"]);  // [key] since it's a 
//array inside a array then finding the key string [latitude]
    var lon = master([key]["longitude"]); 
    var lat_max = Math.max(lat); 
    var lat_min = Math.min(lat);
    var lon_max = Math.max(lon);
    var lon_min = Math.min(lon);
    var total_max = (lat_max + lon_min);
    var total_min = (lon_max + lon_min);
    var average = (total_max / total_min);
  }
  return average; 
}

Get the average of longitude and latitude.

2 个答案:

答案 0 :(得分:1)

Use map to get the latitude and longitude values into separate arrays, then apply those to min and max, and finally average them:

function findMapCenter(master) {
    var minLat = Math.min(...Object.values(master).map(({ latitude }) => latitude));
    var maxLat = Math.max(...Object.values(master).map(({ latitude }) => latitude));
    var minLon = Math.min(...Object.values(master).map(({ longitude }) => longitude));
    var maxLon = Math.max(...Object.values(master).map(({ latitude }) => latitude));
    return (maxLat + minLat) / (maxLon + minLon);
}

答案 1 :(得分:1)

您还可以使用Array.reduce对数组进行一次迭代,这应该更快一些(如果您从来没有大量输入,则不相关)。我正在根据您提到的API link的输出来编写代码:

// Sample json
const json = [ { "latitude": "-11", "longitude": "-3" }, { "latitude": "-10", "longitude": "-30" }, { "latitude": "1", "longitude": "3" }, { "latitude": "2", "longitude": "-2" }];

function findCenter(json) {
    let [minLat, minLon, maxLat, maxLon] = json.reduce((a, b) => 
      [ +b.latitude  < a[0]  ?  +b.latitude  : a[0],
        +b.longitude < a[1]  ?  +b.longitude : a[1],
        +b.latitude  > a[2]  ?  +b.latitude  : a[2],
        +b.longitude > a[3]  ?  +b.longitude : a[3] ]
      , [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER]);
    return (maxLat + minLat) / (maxLon + minLon);
}

console.log(findCenter(json));

警告:如果您的数组为空,此函数将返回:

[Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER]