olanchuy olanchuy - 27 days ago 6
Javascript Question

How to get maximum/minimum boundaries with array of coordinates

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 }

Answer

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);

Comments