最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get maximumminimum boundaries with array of coordinates - Stack Overflow

programmeradmin5浏览0评论

Can anyone help me with the logic on how should I get the maximum/minimum coordinates, with an array of coodinates? What I'm trying to get is the longest distance it can get out of those array of coordinates. Ex.

    var coordinates = [{
       lat: -231,
       lng: 223l
    }, {
       lat: 43,
       lng: -4323
    }, {
       lat: 42312,
       lng: -231
    }, {
       lat: 435345,
       lng: -6563
    }]

    // some filter calculation here...


    // This is what I need
    var min_coords = { lat, lng }
    var max_coords = { lat, lng }

Can anyone help me with the logic on how should I get the maximum/minimum coordinates, with an array of coodinates? What I'm trying to get is the longest distance it can get out of those array of coordinates. Ex.

    var coordinates = [{
       lat: -231,
       lng: 223l
    }, {
       lat: 43,
       lng: -4323
    }, {
       lat: 42312,
       lng: -231
    }, {
       lat: 435345,
       lng: -6563
    }]

    // some filter calculation here...


    // This is what I need
    var min_coords = { lat, lng }
    var max_coords = { lat, lng }
Share Improve this question asked Nov 9, 2016 at 11:33 olanchuyolanchuy 5151 gold badge4 silver badges14 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You can create arrays of the values, and then use Math.max and Math.min to get the highest and lowest values

var coordinates = [{
    lat: -231,
    lng: 223
}, {
    lat: 43,
    lng: -4323
}, {
    lat: 42312,
    lng: -231
}, {
    lat: 435345,
    lng: -6563
}]

var lat = coordinates.map(function(p) {return p.lat});
var lng = coordinates.map(function(p) {return p.lng});

var min_coords = {
    lat : Math.min.apply(null, lat),
    lng : Math.min.apply(null, lng)
}
var max_coords = {
    lat : Math.max.apply(null, lat),
    lng : Math.max.apply(null, lng)
}

console.log(min_coords);
console.log(max_coords);

A solution using Array.prototype.reduce to filter through the array for the min and max values - demo below:

var coordinates=[{lat:-231,lng:223},{lat:43,lng:-4323},{lat:42312,lng:-231},{lat:435345,lng:-6563}];

var result = coordinates.reduce(function(prev,curr){
   if(curr.lat < prev.min_cords.lat)
     prev.min_cords.lat = curr.lat;
  if(curr.lat > prev.max_cords.lat)
     prev.max_cords.lat = curr.lat;
  if(curr.lng < prev.min_cords.lng)
     prev.min_cords.lng = curr.lng;
  if(curr.lng > prev.max_cords.lng)
     prev.max_cords.lng = curr.lng;
  return prev;
},{min_cords:{lat:Infinity,lng:Infinity},max_cords:{lat:-Infinity,lng:-Infinity}});

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

发布评论

评论列表(0)

  1. 暂无评论